<?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
{
    public function up(): void
    {
        $driver = DB::getDriverName();

        if ($driver === 'sqlite') {
            Schema::table('receipt_consecutives', function (Blueprint $table) {
                $table->string('receipt_type', 10)->default('01')->after('id');
                $table->smallInteger('establishment')->default(1)->after('receipt_type');
                $table->integer('terminal')->default(1)->after('establishment');
            });
        } else {
            DB::statement("ALTER TABLE receipt_consecutives ADD COLUMN IF NOT EXISTS receipt_type VARCHAR(10) NOT NULL DEFAULT '01'");
            DB::statement('ALTER TABLE receipt_consecutives ADD COLUMN IF NOT EXISTS establishment SMALLINT NOT NULL DEFAULT 1');
            DB::statement('ALTER TABLE receipt_consecutives ADD COLUMN IF NOT EXISTS terminal INTEGER NOT NULL DEFAULT 1');
        }

        Schema::table('receipt_consecutives', function (Blueprint $table) {
            $table->unique(['receipt_type', 'establishment', 'terminal'], 'consecutives_type_est_term_unique');
        });
    }

    public function down(): void
    {
        Schema::table('receipt_consecutives', function (Blueprint $table) {
            $table->dropUnique('consecutives_type_est_term_unique');
            $table->dropColumn(['receipt_type', 'establishment', 'terminal']);
        });
    }
};
