<?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
    {
        // Evolve the existing `templates` table into `contact_templates`.
        // User confirmed no production rows — this is effectively a rename + schema change.
        // If rows do exist, the backfill is defensive and requires
        // config('contact.templates_backfill_solicitor_id') to be set.

        $rowCount = Schema::hasTable('templates') ? DB::table('templates')->count() : 0;
        $backfillSolicitorId = config('contact.templates_backfill_solicitor_id');

        if ($rowCount > 0 && empty($backfillSolicitorId)) {
            throw new RuntimeException(
                "Cannot migrate templates → contact_templates: {$rowCount} row(s) exist but "
                . 'config("contact.templates_backfill_solicitor_id") is not set. '
                . 'Set CONTACT_TEMPLATES_BACKFILL_SOLICITOR_ID in .env and retry.'
            );
        }

        if (Schema::hasTable('templates')) {
            Schema::rename('templates', 'contact_templates');
        } else {
            Schema::create('contact_templates', function (Blueprint $t) {
                $t->id();
                $t->uuid('slug');
                $t->foreignId('category_id')->nullable()->constrained('contact_categories')->nullOnDelete();
                $t->string('title');
                $t->string('subject')->nullable();
                $t->text('content')->nullable();
                $t->string('type')->default('email');
                $t->timestamps();
                $t->softDeletes();
            });
        }

        Schema::table('contact_templates', function (Blueprint $t) {
            $t->foreignId('solicitor_id')->nullable()->after('id')->constrained()->cascadeOnDelete();
            $t->string('name')->nullable()->after('slug');
            $t->string('key')->nullable()->after('name');
            $t->string('channel', 16)->nullable()->after('key');
            $t->boolean('is_active')->default(true)->after('channel');
            $t->boolean('allow_manual_send')->default(true)->after('is_active');
            $t->boolean('allow_automatic_send')->default(false)->after('allow_manual_send');
            $t->longText('body_text_template')->nullable()->after('subject');
            $t->longText('body_html_template')->nullable()->after('body_text_template');
            $t->foreignId('default_sender_email_id')->nullable()->after('body_html_template')
                ->constrained('solicitor_email_senders')->nullOnDelete();
            $t->foreignId('default_sender_phone_id')->nullable()->after('default_sender_email_id')
                ->constrained('solicitor_phone_numbers')->nullOnDelete();
            $t->string('applies_to_type')->nullable()->after('default_sender_phone_id');
            $t->string('description')->nullable()->after('applies_to_type');
            $t->json('config')->nullable()->after('description');
        });

        if ($rowCount > 0) {
            DB::table('contact_templates')->whereNull('solicitor_id')
                ->update([
                    'solicitor_id' => $backfillSolicitorId,
                    'channel' => DB::raw("COALESCE(NULLIF(`type`, ''), 'email')"),
                    'body_html_template' => DB::raw('`content`'),
                    'body_text_template' => DB::raw('`content`'),
                    'name' => DB::raw("COALESCE(NULLIF(`title`, ''), 'Untitled')"),
                ]);
        }

        Schema::table('contact_templates', function (Blueprint $t) {
            $t->foreignId('solicitor_id')->nullable(false)->change();
        });

        if (Schema::hasColumn('contact_templates', 'content')) {
            Schema::table('contact_templates', function (Blueprint $t) {
                $t->dropColumn('content');
            });
        }
        if (Schema::hasColumn('contact_templates', 'type')) {
            Schema::table('contact_templates', function (Blueprint $t) {
                $t->dropColumn('type');
            });
        }
        if (Schema::hasColumn('contact_templates', 'title')) {
            Schema::table('contact_templates', function (Blueprint $t) {
                $t->dropColumn('title');
            });
        }

        Schema::table('contact_templates', function (Blueprint $t) {
            $t->index(['solicitor_id', 'channel', 'is_active']);
            $t->unique(['solicitor_id', 'key'], 'contact_templates_solicitor_key_unique');
        });
    }

    public function down(): void
    {
        Schema::table('contact_templates', function (Blueprint $t) {
            $t->dropUnique('contact_templates_solicitor_key_unique');
            $t->dropIndex(['solicitor_id', 'channel', 'is_active']);
            $t->dropForeign(['default_sender_email_id']);
            $t->dropForeign(['default_sender_phone_id']);
            $t->dropForeign(['solicitor_id']);
            $t->dropColumn([
                'solicitor_id', 'name', 'key', 'channel',
                'is_active', 'allow_manual_send', 'allow_automatic_send',
                'body_text_template', 'body_html_template',
                'default_sender_email_id', 'default_sender_phone_id',
                'applies_to_type', 'description', 'config',
            ]);
            $t->string('title')->nullable();
            $t->text('content')->nullable();
            $t->string('type')->default('email');
        });

        Schema::rename('contact_templates', 'templates');
    }
};
