<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $driver = DB::getDriverName();

        if (DB::table('payments')->where('payment_method', 'boleto')->exists()) {
            throw new RuntimeException('Remova ou migre pagamentos boleto antes de restringir payment_method para credit_card e pix.');
        }

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE payments DROP CONSTRAINT IF EXISTS payments_payment_method_check');
            DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_payment_method_check CHECK (payment_method IN ('credit_card', 'pix'))");

            return;
        }

        if ($driver === 'mysql') {
            DB::statement("ALTER TABLE payments MODIFY payment_method ENUM('credit_card', 'pix') NOT NULL");
        }
    }

    public function down(): void
    {
        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE payments DROP CONSTRAINT IF EXISTS payments_payment_method_check');
            DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_payment_method_check CHECK (payment_method IN ('credit_card', 'pix', 'boleto'))");

            return;
        }

        if ($driver === 'mysql') {
            DB::statement("ALTER TABLE payments MODIFY payment_method ENUM('credit_card', 'pix', 'boleto') NOT NULL");
        }
    }
};
