<?php

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

/**
 * email_signatures — per-account email signature blocks that
 * EmailSendService auto-appends to outgoing mail.
 *
 * !!! CRITICAL: This migration MUST stay idempotent !!!
 * The original 0001_01_01_000005_create_email_accounts_table.php
 * migration creates this same table on every fresh install. Customers
 * upgrading from v1.2 / v1.3 already have the table. Without the
 * Schema::hasTable() guard the v1.4 update wizard fails on step 4
 * (Run database migrations) with "1050 Table email_signatures
 * already exists" — and the whole update is blocked.
 */
return new class extends Migration {
    public function up(): void
    {
        // Already created by 0001_01_01_000005_create_email_accounts_table
        // on every fresh install — skip the CREATE so the update wizard
        // doesn't error out on existing customers.
        if (Schema::hasTable('email_signatures')) {
            return;
        }

        Schema::create('email_signatures', function (Blueprint $table) {
            $table->id();
            $table->foreignId('email_account_id')
                ->constrained('email_accounts')
                ->cascadeOnDelete();
            $table->string('name', 100);
            $table->longText('content_html');
            $table->boolean('is_default')->default(false);
            $table->boolean('append_to_new')->default(true);
            $table->boolean('append_to_replies')->default(true);
            $table->timestamps();

            $table->index(['email_account_id', 'is_default'], 'email_signatures_account_default_idx');
        });
    }

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