<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Tambah kolom budget harian (model per-klik inline) ke ads.
     *
     * Mengganti model lama (credit = cap klik seumur hidup, dibayar upfront) dengan
     * budget harian rupiah: cap_klik_harian = budget_harian / rate, dipotong per-klik
     * inline dari saldo. Sisa cap roll ke hari berikutnya via cron.
     */
    public function up(): void
    {
        Schema::table('ads', function (Blueprint $table) {
            $table->unsignedInteger('budget_harian')->nullable()->after('credit');
            $table->unsignedInteger('klik_hari_ini')->default(0)->after('klik');
            $table->date('klik_tanggal')->nullable()->after('klik_hari_ini');
            $table->unsignedInteger('rollover_klik')->default(0)->after('klik_tanggal');
            $table->string('pause_reason', 20)->nullable()->after('is_paused');
        });

        // Backfill ads lama: budget_harian = credit × rate (default 100).
        // Ads Selesai (status=3) dibiarkan null — sudah selesai, tidak tayang lagi.
        DB::table('ads')
            ->whereNull('budget_harian')
            ->where('status', '!=', 3)
            ->where('credit', '>', 0)
            ->update(['budget_harian' => DB::raw('credit * 100')]);

        // Index rotator hot path: status + kategori + is_paused.
        Schema::table('ads', function (Blueprint $table) {
            $table->index(['status', 'kategori_id', 'is_paused'], 'ads_rotatable_index');
        });
    }

    public function down(): void
    {
        Schema::table('ads', function (Blueprint $table) {
            $table->dropIndex('ads_rotatable_index');
            $table->dropColumn(['budget_harian', 'klik_hari_ini', 'klik_tanggal', 'rollover_klik', 'pause_reason']);
        });
    }
};
