<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Creates the email_templates table for reusable email templates.
     * 
     * Requirements: 3.1, 3.8
     */
    public function up(): void
    {
        Schema::create('email_templates', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Template identification (respecting 191 char limit for indexed columns)
            $table->string('name', 191)->comment('Human-readable template name');
            $table->string('slug', 191)->unique()->comment('URL-friendly identifier');

            // Template content
            $table->string('subject', 191)->comment('Default email subject line');
            $table->text('preheader')->nullable()->comment('Preview text shown in email clients');
            $table->longText('html_content')->comment('HTML email content');
            $table->text('text_content')->nullable()->comment('Plain text version for compatibility');

            // Template description for admin reference
            $table->text('description')->nullable()->comment('Description of when to use this template');

            // Active status
            $table->boolean('is_active')
                ->default(true)
                ->comment('Whether template is available for use');

            // System template flag (cannot be deleted by managers)
            $table->boolean('is_system')
                ->default(false)
                ->comment('System templates cannot be deleted');

            // Who created this template
            $table->foreignId('created_by')
                ->nullable()
                ->constrained('users')
                ->nullOnDelete()
                ->comment('User who created the template');

            // Usage tracking
            $table->integer('usage_count')->default(0)->comment('Number of times template has been used');

            // Available placeholders (stored as JSON for documentation)
            $table->json('placeholders')->nullable()->comment('Available placeholder variables');

            // Standard timestamps
            $table->timestamps();
            $table->softDeletes();

            // Indexes for performance
            $table->index('is_active');
            $table->index('is_system');
            $table->index('slug');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('email_templates');
    }
};
