<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // For SQLite, we need to recreate the table
        // For MySQL/PostgreSQL, we use ALTER TABLE
        
        if (DB::getDriverName() === 'sqlite') {
            // SQLite doesn't support MODIFY COLUMN, so we need to recreate
            Schema::table('sales', function ($table) {
                // Update data first
                DB::table('sales')->where('channel', 'manual')->update(['channel' => 'pos']);
                DB::table('sales')->where('channel', 'grab')->update(['channel' => 'vibe24jam']);
            });
        } else {
            // Step 1: Temporarily change to VARCHAR to allow data migration
            DB::statement("ALTER TABLE sales MODIFY COLUMN channel VARCHAR(20) DEFAULT 'pos'");

            // Step 2: Update existing records to new channel names
            DB::table('sales')->where('channel', 'manual')->update(['channel' => 'pos']);
            DB::table('sales')->where('channel', 'grab')->update(['channel' => 'vibe24jam']);

            // Step 3: Convert to final ENUM with new values
            DB::statement("ALTER TABLE sales MODIFY COLUMN channel ENUM('vibe24jam', 'blibli', 'tokopedia', 'shopee', 'pos') DEFAULT 'pos'");
        }
    }

    public function down(): void
    {
        if (DB::getDriverName() === 'sqlite') {
            Schema::table('sales', function ($table) {
                // Revert data
                DB::table('sales')->where('channel', 'pos')->update(['channel' => 'manual']);
                DB::table('sales')->where('channel', 'vibe24jam')->update(['channel' => 'grab']);
            });
        } else {
            // Step 1: Temporarily change to VARCHAR
            DB::statement("ALTER TABLE sales MODIFY COLUMN channel VARCHAR(20) DEFAULT 'manual'");

            // Step 2: Revert data
            DB::table('sales')->where('channel', 'pos')->update(['channel' => 'manual']);
            DB::table('sales')->where('channel', 'vibe24jam')->update(['channel' => 'grab']);

            // Step 3: Restore original ENUM
            DB::statement("ALTER TABLE sales MODIFY COLUMN channel ENUM('tokopedia', 'shopee', 'blibli', 'grab', 'manual') DEFAULT 'manual'");
        }
    }
};
