<?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('activities', function (Blueprint $table) {
            $table->string('legacy_type')->nullable()->index();
            $table->unsignedBigInteger('legacy_id')->nullable()->index();
            $table->uuid('tracking_token')->nullable()->unique();
            $table->uuid('reply_token')->nullable()->unique();
            $table->uuid('calendar_uid')->nullable()->unique();
            $table->string('external_calendar_id')->nullable();
            $table->string('calendar_sync_status')->nullable();
            $table->text('calendar_sync_error')->nullable();
            $table->unique(['legacy_type', 'legacy_id'], 'activities_legacy_unique');
        });

        Schema::create('email_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('business_id')->index();
            $table->foreignId('owner_id')->nullable()->index();
            $table->string('name');
            $table->string('subject');
            $table->longText('body');
            $table->string('category')->nullable();
            $table->boolean('active')->default(true);
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('email_tracking_events', function (Blueprint $table) {
            $table->id();
            $table->foreignId('activity_id')->index();
            $table->string('event');
            $table->string('message_id')->nullable();
            $table->string('sender')->nullable();
            $table->text('content')->nullable();
            $table->json('metadata')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('email_tracking_events');
        Schema::dropIfExists('email_templates');
        Schema::table('activities', function (Blueprint $table) {
            $table->dropUnique('activities_legacy_unique');
            $table->dropUnique(['tracking_token']);
            $table->dropUnique(['reply_token']);
            $table->dropUnique(['calendar_uid']);
            $table->dropColumn(['legacy_type','legacy_id','tracking_token','reply_token','calendar_uid',
                'external_calendar_id','calendar_sync_status','calendar_sync_error']);
        });
    }
};
