<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tax_rates', function (Blueprint $table) {
            if (! Schema::hasColumn('tax_rates', 'has_surcharge')) {
                $table->boolean('has_surcharge')->default(false)->after('rate');
            }
            if (! Schema::hasColumn('tax_rates', 'surcharge_rate')) {
                $table->decimal('surcharge_rate', 5, 2)->nullable()->after('has_surcharge');
            }
            if (! Schema::hasColumn('tax_rates', 'is_group')) {
                $table->boolean('is_group')->default(false)->after('type');
            }
            if (! Schema::hasColumn('tax_rates', 'is_selectable')) {
                $table->boolean('is_selectable')->default(true)->after('is_group');
            }
        });

        if (! Schema::hasTable('tax_group_members')) {
            Schema::create('tax_group_members', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tax_group_id')->constrained('tax_rates')->cascadeOnDelete();
                $table->foreignId('tax_rate_id')->constrained('tax_rates')->cascadeOnDelete();
                $table->unsignedTinyInteger('sort_order')->default(0);
                $table->timestamps();

                $table->unique(['tax_group_id', 'tax_rate_id']);
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('tax_group_members');

        Schema::table('tax_rates', function (Blueprint $table) {
            $table->dropColumn(['has_surcharge', 'surcharge_rate', 'is_group', 'is_selectable']);
        });
    }
};
