-- Kredi ve süre yönetimi sistemi

-- Tenants tablosuna kredi ve süre alanları ekle
ALTER TABLE tenants 
ADD COLUMN message_credits INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'Mesaj gönderme kredisi' AFTER max_daily_messages,
ADD COLUMN panel_expires_at TIMESTAMP NULL DEFAULT NULL COMMENT 'Panel erişim bitiş tarihi' AFTER trial_ends_at,
ADD COLUMN credits_updated_at TIMESTAMP NULL DEFAULT NULL COMMENT 'Son kredi güncelleme zamanı' AFTER panel_expires_at;

-- Kredi hareketleri tablosu
CREATE TABLE IF NOT EXISTS credit_transactions (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    transaction_type ENUM('credit', 'debit', 'admin_add', 'admin_remove', 'campaign_use') NOT NULL,
    amount INT NOT NULL COMMENT 'Pozitif=ekleme, Negatif=kullanım',
    balance_before INT NOT NULL,
    balance_after INT NOT NULL,
    description VARCHAR(500) NULL,
    campaign_id BIGINT UNSIGNED NULL,
    admin_user_id BIGINT UNSIGNED NULL COMMENT 'İşlemi yapan admin',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON DELETE SET NULL,
    FOREIGN KEY (admin_user_id) REFERENCES users(id) ON DELETE SET NULL,
    KEY idx_credit_transactions_tenant (tenant_id),
    KEY idx_credit_transactions_type (transaction_type),
    KEY idx_credit_transactions_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Panel erişim logları
CREATE TABLE IF NOT EXISTS panel_access_logs (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    action_type ENUM('extend', 'reduce', 'activate', 'suspend') NOT NULL,
    old_expires_at TIMESTAMP NULL,
    new_expires_at TIMESTAMP NULL,
    days_changed INT NULL COMMENT 'Kaç gün eklendi/çıkarıldı',
    admin_user_id BIGINT UNSIGNED NOT NULL,
    note VARCHAR(500) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (admin_user_id) REFERENCES users(id) ON DELETE CASCADE,
    KEY idx_panel_access_tenant (tenant_id),
    KEY idx_panel_access_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
