# BidCast — Instagram Live Mezat Sistemi

## 🎯 Vizyon
E-ticaret sitelerine entegre edilebilen, Instagram canlı yayınlarında gerçek zamanlı mezat/açık artırma yönetimi yapan SaaS platform.

---

## 📐 Mimari Genel Bakış

```
┌─────────────────────────────────────────────────────────────────┐
│                        BidCast Platform                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐  │
│  │  Instagram    │───▶│  BidCast     │───▶│  Broadcaster     │  │
│  │  Webhooks     │    │  Core API    │    │  Dashboard       │  │
│  │  (Comments)   │    │  (Node.js)   │    │  (React/Next.js) │  │
│  └──────────────┘    └──────┬───────┘    └──────────────────┘  │
│                             │                                   │
│                    ┌────────┴────────┐                          │
│                    │                 │                           │
│              ┌─────▼─────┐    ┌─────▼──────┐                   │
│              │ WebSocket  │    │  REST API   │                  │
│              │ Server     │    │  (Webhook   │                  │
│              │ (Socket.io)│    │   Outgoing) │                  │
│              └─────┬──────┘    └─────┬──────┘                   │
│                    │                 │                           │
│              ┌─────▼─────┐    ┌─────▼──────┐                   │
│              │ Broadcaster│    │  3rd Party  │                  │
│              │ Panel      │    │  E-commerce │                  │
│              │ (Realtime) │    │  Sites      │                  │
│              └────────────┘    └────────────┘                   │
│                                                                 │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐  │
│  │  PostgreSQL   │    │    Redis     │    │  Bull Queue      │  │
│  │  (Ana DB)     │    │  (Cache +    │    │  (Job Processing)│  │
│  │              │    │   Pub/Sub)   │    │                  │  │
│  └──────────────┘    └──────────────┘    └──────────────────┘  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## 🔄 Yorum Akışı (Comment Flow)

```
Instagram Live Comment
        │
        ▼
Meta Webhook (POST /webhooks/instagram)
        │
        ▼
Comment Parser & Validator
        │
        ├── "aldım" / "ALDIM" / "Aldım" algılandı
        │       │
        │       ▼
        │   User Matcher (IG username → Site user)
        │       │
        │       ├── Eşleşme VAR → Cart Service (sepete ekle)
        │       │       │
        │       │       ├── Stok var → ✅ Sepete eklendi
        │       │       │       │
        │       │       │       ├── WebSocket → Panel'e bildir
        │       │       │       ├── Webhook → E-ticaret sitesine bildir
        │       │       │       └── (Opsiyonel) IG Comment Reply
        │       │       │
        │       │       └── Stok yok → ⏳ Bekleme listesine al
        │       │
        │       └── Eşleşme YOK → Kayıt et (unmatched_bids tablosu)
        │
        ├── "500" / "500TL" algılandı (Açık artırma modu)
        │       │
        │       ▼
        │   Bid Validator (min. artış, geçerli fiyat?)
        │       │
        │       ├── Geçerli → Bid kaydı + WebSocket güncelleme
        │       └── Geçersiz → Yoksay (log tut)
        │
        └── Normal yorum → Dashboard'da göster
```

---

## 🗂️ Veritabanı Şeması (Temel Tablolar)

### Tenants (Bayiler)
```sql
tenants
├── id (UUID, PK)
├── name                    -- Bayi adı
├── slug                    -- URL-friendly isim
├── api_key                 -- API anahtarı
├── api_secret              -- API secret (hashed)
├── webhook_url             -- Ürün sepete eklendiğinde bildirim URL'i
├── webhook_secret          -- Webhook imza doğrulama
├── ig_account_id           -- Instagram Professional Account ID
├── ig_access_token         -- Encrypted long-lived token
├── ig_page_id              -- Facebook Page ID
├── settings (JSONB)        -- Dil, tema, bildirim tercihleri vs.
├── plan                    -- free / pro / enterprise
├── is_active
├── created_at
└── updated_at
```

### Products (Ürünler)
```sql
products
├── id (UUID, PK)
├── tenant_id (FK → tenants)
├── external_id             -- Dış sitedeki ürün ID
├── name
├── description
├── image_url
├── price                   -- Sabit fiyat modu için
├── starting_price          -- Açık artırma modu için
├── min_bid_increment       -- Minimum artış miktarı
├── stock_quantity
├── status                  -- draft / ready / active / sold / cancelled
├── created_at
└── updated_at
```

### Live Sessions (Canlı Yayınlar)
```sql
live_sessions
├── id (UUID, PK)
├── tenant_id (FK → tenants)
├── ig_live_video_id        -- Instagram live video ID
├── title
├── status                  -- pending / live / ended
├── started_at
├── ended_at
├── total_viewers
├── total_comments
├── total_sales
├── settings (JSONB)        -- Auto-reply aktif mi, dil vs.
└── created_at
```

### Auction Items (Mezat Kalemleri)
```sql
auction_items
├── id (UUID, PK)
├── live_session_id (FK → live_sessions)
├── product_id (FK → products)
├── mode                    -- fixed_price / auction
├── starting_price
├── current_price           -- Anlık en yüksek teklif
├── min_bid_increment
├── time_limit_seconds      -- NULL = manuel kapanış
├── status                  -- queued / active / countdown / sold / cancelled
├── activated_at
├── closed_at
├── winner_user_id (FK)
└── created_at
```

### Bids (Teklifler / Aldım Kayıtları)
```sql
bids
├── id (UUID, PK)
├── auction_item_id (FK → auction_items)
├── user_id (FK → users, nullable)
├── ig_username              -- Instagram kullanıcı adı
├── ig_comment_id            -- Instagram yorum ID
├── bid_type                 -- claim (aldım) / bid (fiyat teklifi)
├── amount                   -- Teklif tutarı (sabit fiyatta ürün fiyatı)
├── status                   -- pending / won / lost / cancelled
├── is_matched               -- Siteye eşleştirildi mi?
├── comment_timestamp        -- IG'deki yorum zamanı
├── processed_at
└── created_at
```

### Users (Kullanıcılar)
```sql
users
├── id (UUID, PK)
├── tenant_id (FK → tenants)
├── email
├── ig_username              -- Manuel giriş
├── ig_user_id               -- OAuth ile bağlanınca
├── ig_auth_method           -- manual / oauth
├── display_name
├── phone
├── is_verified
├── trust_score              -- Aldım yazıp almama oranı
├── total_purchases
├── total_no_shows           -- Aldım deyip almama sayısı
├── is_blocked
├── created_at
└── updated_at
```

### Cart Events (Sepet Olayları)
```sql
cart_events
├── id (UUID, PK)
├── tenant_id (FK → tenants)
├── bid_id (FK → bids)
├── user_id (FK → users)
├── product_id (FK → products)
├── external_cart_id         -- Dış sitedeki sepet/order ID
├── status                   -- pending / sent / confirmed / failed
├── webhook_response (JSONB)
├── created_at
└── updated_at
```

---

## 🧩 Modüller & Dosya Yapısı

```
bidcast/
├── package.json
├── .env.example
├── docker-compose.yml           -- PostgreSQL + Redis
├── tsconfig.json
│
├── src/
│   ├── index.ts                 -- App entry point
│   ├── config/
│   │   ├── database.ts
│   │   ├── redis.ts
│   │   ├── instagram.ts
│   │   └── constants.ts
│   │
│   ├── api/                     -- REST API routes
│   │   ├── routes/
│   │   │   ├── auth.routes.ts
│   │   │   ├── tenant.routes.ts
│   │   │   ├── product.routes.ts
│   │   │   ├── session.routes.ts
│   │   │   ├── auction.routes.ts
│   │   │   ├── user.routes.ts
│   │   │   ├── webhook.routes.ts       -- Incoming IG webhooks
│   │   │   └── integration.routes.ts   -- Outgoing API for e-commerce
│   │   │
│   │   └── middleware/
│   │       ├── auth.middleware.ts
│   │       ├── apiKey.middleware.ts
│   │       ├── rateLimiter.ts
│   │       └── validate.ts
│   │
│   ├── services/
│   │   ├── instagram/
│   │   │   ├── webhook.service.ts      -- IG webhook processing
│   │   │   ├── comment.parser.ts       -- "aldım" / fiyat algılama
│   │   │   ├── graph-api.service.ts    -- IG Graph API calls
│   │   │   └── auth.service.ts         -- OAuth flow
│   │   │
│   │   ├── auction/
│   │   │   ├── auction.service.ts      -- Mezat yönetimi
│   │   │   ├── bid.service.ts          -- Teklif işleme
│   │   │   ├── timer.service.ts        -- Geri sayım yönetimi
│   │   │   └── stock.service.ts        -- Stok kontrolü
│   │   │
│   │   ├── cart/
│   │   │   ├── cart.service.ts         -- Sepete ekleme orchestration
│   │   │   └── webhook-sender.ts       -- Dış siteye webhook gönderimi
│   │   │
│   │   ├── user/
│   │   │   ├── user.service.ts
│   │   │   └── matcher.service.ts      -- IG username ↔ site user eşleştirme
│   │   │
│   │   ├── notification/
│   │   │   ├── email.service.ts
│   │   │   └── ig-reply.service.ts     -- IG yorumuna otomatik yanıt
│   │   │
│   │   └── tenant/
│   │       ├── tenant.service.ts
│   │       └── billing.service.ts
│   │
│   ├── websocket/
│   │   ├── socket.server.ts            -- Socket.io server
│   │   ├── handlers/
│   │   │   ├── dashboard.handler.ts    -- Panel real-time updates
│   │   │   └── auction.handler.ts      -- Mezat real-time events
│   │   └── rooms.ts                    -- Tenant-based rooms
│   │
│   ├── jobs/                           -- Bull queue jobs
│   │   ├── process-comment.job.ts
│   │   ├── send-webhook.job.ts
│   │   ├── send-email.job.ts
│   │   └── cleanup.job.ts
│   │
│   ├── db/
│   │   ├── migrations/
│   │   ├── seeds/
│   │   └── models/                     -- Prisma / TypeORM models
│   │
│   ├── i18n/
│   │   ├── tr.json
│   │   └── en.json
│   │
│   └── utils/
│       ├── crypto.ts                   -- API key generation, encryption
│       ├── logger.ts
│       └── helpers.ts
│
├── dashboard/                          -- Frontend (React/Next.js)
│   ├── package.json
│   ├── src/
│   │   ├── pages/
│   │   │   ├── login.tsx
│   │   │   ├── dashboard.tsx           -- Ana sayfa / istatistikler
│   │   │   ├── products.tsx            -- Ürün yönetimi
│   │   │   ├── live.tsx                -- Canlı yayın kontrol paneli
│   │   │   ├── auctions.tsx            -- Geçmiş mezatlar
│   │   │   ├── users.tsx               -- Kullanıcı yönetimi
│   │   │   ├── settings.tsx            -- Ayarlar
│   │   │   └── integration.tsx         -- API key, webhook ayarları
│   │   │
│   │   ├── components/
│   │   │   ├── LiveCommentFeed.tsx      -- Gerçek zamanlı yorum akışı
│   │   │   ├── AuctionControl.tsx       -- Ürün aç/kapat/timer
│   │   │   ├── BidList.tsx              -- Teklif listesi
│   │   │   ├── ProductQueue.tsx         -- Sıradaki ürünler
│   │   │   ├── StockIndicator.tsx
│   │   │   └── UserMatchStatus.tsx
│   │   │
│   │   └── lib/
│   │       ├── socket.ts               -- Socket.io client
│   │       ├── api.ts                  -- API client
│   │       └── i18n.ts
│   │
│   └── public/
│       └── locales/
│           ├── tr/
│           └── en/
│
├── plugins/                            -- E-ticaret eklentileri
│   ├── woocommerce/                    -- WordPress/WooCommerce plugin
│   │   └── bidcast-woo/
│   │       ├── bidcast-woo.php
│   │       └── includes/
│   │
│   └── shopify/                        -- (İleride) Shopify App
│
├── sdk/                                -- Developer SDK
│   ├── js/
│   │   └── bidcast-sdk.js              -- npm install bidcast
│   └── php/
│       └── BidCast.php                 -- Composer package
│
└── docs/
    ├── PROJECT_PLAN.md                 -- (Bu dosya)
    ├── API.md                          -- API dokümantasyonu
    ├── INTEGRATION_GUIDE.md            -- Entegrasyon rehberi
    └── INSTAGRAM_SETUP.md             -- IG Professional hesap kurulum rehberi
```

---

## 🔌 Entegrasyon API (Dış Siteler İçin)

### Webhook: Sepete Ekleme Bildirimi
Dış site bir webhook URL tanımlar. Bir ürün sepete eklendiğinde BidCast şu payload'ı gönderir:

```json
POST {tenant.webhook_url}
Headers:
  X-BidCast-Signature: sha256=...  (webhook_secret ile HMAC)
  X-BidCast-Event: cart.item_added
  Content-Type: application/json

{
  "event": "cart.item_added",
  "timestamp": "2026-04-13T15:30:00Z",
  "data": {
    "auction_item_id": "uuid",
    "product": {
      "external_id": "SKU-001",
      "name": "Osmanlı Gümüş Tespih",
      "price": 1500.00,
      "currency": "TRY"
    },
    "buyer": {
      "ig_username": "antikaci_mehmet",
      "user_id": "uuid-or-null",
      "email": "mehmet@example.com"
    },
    "session": {
      "ig_live_video_id": "17854360229135607",
      "title": "Pazar Mezadı"
    }
  }
}
```

### REST API Endpoints (Bayiler İçin)
```
Auth:
  POST   /api/v1/auth/register          -- Bayi kaydı
  POST   /api/v1/auth/login
  POST   /api/v1/auth/refresh

Products:
  GET    /api/v1/products                -- Ürün listesi
  POST   /api/v1/products                -- Ürün ekle
  PUT    /api/v1/products/:id
  DELETE /api/v1/products/:id

Sessions:
  POST   /api/v1/sessions/start          -- Yayın başlat (IG live ID ile)
  PUT    /api/v1/sessions/:id/end        -- Yayın sonlandır
  GET    /api/v1/sessions/:id/stats      -- Yayın istatistikleri

Auctions:
  POST   /api/v1/auctions/activate       -- Ürünü mezata aç
  PUT    /api/v1/auctions/:id/close      -- Mezatı kapat
  GET    /api/v1/auctions/:id/bids       -- Teklifleri listele

Users:
  GET    /api/v1/users                   -- Kullanıcılar
  GET    /api/v1/users/:id/history       -- Satın alma geçmişi
  PUT    /api/v1/users/:id/block         -- Kullanıcı engelle

Integration (Dış siteler için — API Key auth):
  GET    /api/v1/integration/cart-events  -- Sepet olayları
  POST   /api/v1/integration/confirm      -- Sepet onayı (site tarafından)
  POST   /api/v1/integration/users/link   -- Kullanıcı eşleştirme
```

---

## ⚡ WebSocket Events (Panel Real-time)

```
Server → Client:
  comment:new          -- Yeni yorum geldi
  bid:new              -- Yeni teklif/aldım
  bid:won              -- Kazanan belirlendi
  auction:started      -- Mezat başladı
  auction:countdown    -- Geri sayım güncelleme
  auction:ended        -- Mezat bitti
  stock:updated        -- Stok değişti
  user:matched         -- Kullanıcı eşleştirildi
  cart:added           -- Sepete eklendi

Client → Server:
  auction:activate     -- Ürünü mezata aç
  auction:close        -- Mezatı kapat
  auction:extend       -- Süre uzat
  session:start        -- Yayın takibi başlat
  session:end          -- Yayın takibi bitir
```

---

## 🛡️ Güvenlik

1. **API Key + Secret**: Her bayi için benzersiz, secret hashed (bcrypt)
2. **Webhook İmza**: HMAC-SHA256 ile webhook payload doğrulama
3. **IG Token Encryption**: AES-256-GCM ile DB'de şifreli
4. **Rate Limiting**: IP + API Key bazlı
5. **CORS**: Tenant bazlı origin kontrolü
6. **Input Validation**: Zod schema validation
7. **SQL Injection**: Prisma ORM (parameterized queries)
8. **Meta Webhook Verification**: Hub challenge + app secret doğrulama

---

## 📊 Yol Haritası

### Faz 1: Temel Altyapı (Hafta 1-2)
- [ ] Proje scaffold (Node.js + TypeScript + Fastify)
- [ ] PostgreSQL + Redis + Prisma setup
- [ ] Temel tenant/auth sistemi
- [ ] Meta App oluşturma + IG OAuth flow
- [ ] Instagram Webhook altyapısı (comment subscription)

### Faz 2: Mezat Motoru (Hafta 3-4)
- [ ] Comment parser ("aldım" + fiyat algılama)
- [ ] Sabit fiyat modu (ilk gelen alır)
- [ ] Açık artırma modu (fiyat teklifleri)
- [ ] Stok yönetimi
- [ ] Timer/geri sayım sistemi
- [ ] User matcher (IG ↔ site kullanıcı)

### Faz 3: Dashboard (Hafta 5-6)
- [ ] Yayıncı paneli (Next.js + dark theme)
- [ ] Gerçek zamanlı yorum akışı (WebSocket)
- [ ] Ürün yönetimi
- [ ] Mezat kontrol paneli
- [ ] Kullanıcı yönetimi + trust score
- [ ] İstatistikler

### Faz 4: Entegrasyon (Hafta 7-8)
- [ ] REST API (dış siteler için)
- [ ] Webhook sender (sepete ekleme bildirimi)
- [ ] JavaScript SDK (npm package)
- [ ] PHP SDK (Composer package)
- [ ] WooCommerce eklentisi
- [ ] Entegrasyon dokümantasyonu

### Faz 5: Çoklu Dil & Polish (Hafta 9)
- [ ] i18n altyapısı (TR + EN)
- [ ] E-posta notification servisi
- [ ] IG otomatik yorum yanıtı
- [ ] Landing page
- [ ] Instagram kurulum rehberi

### Faz 6: Test & Deploy (Hafta 10)
- [ ] E2E testler
- [ ] Load testing
- [ ] Production deploy
- [ ] SSL + domain ayarları
- [ ] Monitoring (health check, error tracking)

---

## 💡 Teknik Kararlar Özeti

| Karar | Seçim | Neden |
|-------|-------|-------|
| Runtime | Node.js + TypeScript | Real-time, WebSocket native |
| Framework | Fastify | Express'ten 2x hızlı, schema validation built-in |
| DB | PostgreSQL | JSONB, UUID, güvenilir |
| Cache/PubSub | Redis | WebSocket scaling, session cache, rate limit |
| Queue | BullMQ | Redis-based, retry logic, delayed jobs |
| ORM | Prisma | Type-safe, migration, seeding |
| Frontend | Next.js + React | SSR, API routes, modern |
| WebSocket | Socket.io | Room support, auto-reconnect |
| IG API | Graph API + Webhooks | Resmi, < 1sn latency |
| Auth | JWT + API Key | Panel: JWT, API: API Key |
| i18n | next-intl | Next.js native i18n |
