<?php

use App\Services\Reports\ReportTemplateDefaults;
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('report_templates', function (Blueprint $table) {
            if (! Schema::hasColumn('report_templates', 'client_id')) {
                $table->foreignId('client_id')->nullable()->after('id')->constrained()->nullOnDelete();
            }

            if (! Schema::hasColumn('report_templates', 'description')) {
                $table->text('description')->nullable()->after('name');
            }

            if (! Schema::hasColumn('report_templates', 'is_default')) {
                $table->boolean('is_default')->default(false)->after('settings');
            }

            if (! Schema::hasColumn('report_templates', 'sort_order')) {
                $table->unsignedSmallInteger('sort_order')->default(100)->after('is_active');
            }
        });

        if (class_exists(ReportTemplateDefaults::class)) {
            app(ReportTemplateDefaults::class)->seedDefaults();
        }
    }

    public function down(): void
    {
        Schema::table('report_templates', function (Blueprint $table) {
            if (Schema::hasColumn('report_templates', 'sort_order')) {
                $table->dropColumn('sort_order');
            }

            if (Schema::hasColumn('report_templates', 'is_default')) {
                $table->dropColumn('is_default');
            }

            if (Schema::hasColumn('report_templates', 'description')) {
                $table->dropColumn('description');
            }

            if (Schema::hasColumn('report_templates', 'client_id')) {
                $table->dropConstrainedForeignId('client_id');
            }
        });
    }
};
