<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1. product_prices: rename 'reject' → 'reject_selling', then add 'reject_capital' rows
        DB::table('product_prices')
            ->where('type', 'reject')
            ->update(['type' => 'reject_selling']);

        // Insert reject_capital rows (price = 0) for each variant that now has reject_selling
        $rejectSellingPrices = DB::table('product_prices')
            ->where('type', 'reject_selling')
            ->get();

        foreach ($rejectSellingPrices as $row) {
            DB::table('product_prices')->insert([
                'variant_id' => $row->variant_id,
                'type' => 'reject_capital',
                'price' => 0,
                'created_at' => $row->created_at,
                'updated_at' => $row->updated_at,
            ]);
        }

        // 2. orders: rename 'reject' → 'reject_selling'
        DB::table('orders')
            ->where('price_type', 'reject')
            ->update(['price_type' => 'reject_selling']);

        // 3. Modify enum columns to reflect new values (MySQL only)
        if (DB::getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE product_prices MODIFY COLUMN type ENUM('distributor','agent','sub_agent','wholesale','retail','tiktok','shopee','capital','reject_capital','reject_selling') NOT NULL");
            DB::statement("ALTER TABLE orders MODIFY COLUMN price_type ENUM('distributor','agent','sub_agent','wholesale','retail','tiktok','shopee','capital','reject_capital','reject_selling') NOT NULL");
        }
    }

    public function down(): void
    {
        // Reverse: rename back and clean up
        DB::table('product_prices')
            ->where('type', 'reject_capital')
            ->delete();

        DB::table('product_prices')
            ->where('type', 'reject_selling')
            ->update(['type' => 'reject']);

        DB::table('orders')
            ->where('price_type', 'reject_selling')
            ->update(['price_type' => 'reject']);

        if (DB::getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE product_prices MODIFY COLUMN type ENUM('distributor','agent','sub_agent','wholesale','retail','tiktok','shopee','capital','reject') NOT NULL");
            DB::statement("ALTER TABLE orders MODIFY COLUMN price_type ENUM('distributor','agent','sub_agent','wholesale','retail','tiktok','shopee','capital','reject') NOT NULL");
        }
    }
};
