<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        // Prefix studio_* avoids clash with Client Portal document_versions / document_comments.
        Schema::create('studio_document_templates', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name');
            $table->string('document_type', 40)->default('custom');
            $table->longText('body_html');
            $table->json('body_json')->nullable();
            $table->boolean('is_default')->default(false);
            $table->boolean('is_system')->default(false);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->index(['tenant_id', 'document_type', 'is_default']);
        });

        Schema::create('business_documents', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('document_type', 40)->default('custom');
            $table->foreignUuid('template_id')->nullable()->constrained('studio_document_templates')->nullOnDelete();
            $table->foreignUuid('deal_id')->nullable()->constrained('sales_deals')->nullOnDelete();
            $table->foreignUuid('contact_id')->constrained('contacts')->cascadeOnDelete();
            $table->foreignUuid('property_id')->nullable()->constrained('properties')->nullOnDelete();
            $table->uuid('owner_id')->nullable();
            $table->foreignUuid('client_portal_id')->nullable();
            $table->uuid('current_version_id')->nullable();
            $table->string('number', 40);
            $table->string('title');
            $table->string('status', 40)->default('draft');
            $table->decimal('amount', 14, 2)->nullable();
            $table->string('currency', 3)->default('BRL');
            $table->text('intro_message')->nullable();
            $table->json('context_snapshot')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamp('shared_at')->nullable();
            $table->timestamp('decided_at')->nullable();
            $table->timestamp('last_viewed_at')->nullable();
            $table->unsignedInteger('view_count')->default(0);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('responsible_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['tenant_id', 'number']);
            $table->index(['tenant_id', 'status']);
            $table->index(['tenant_id', 'document_type']);
            $table->index(['tenant_id', 'deal_id']);
        });

        if (Schema::hasTable('owners')) {
            Schema::table('business_documents', function (Blueprint $table): void {
                $table->foreign('owner_id')->references('id')->on('owners')->nullOnDelete();
            });
        }
        if (Schema::hasTable('client_portals')) {
            Schema::table('business_documents', function (Blueprint $table): void {
                $table->foreign('client_portal_id')->references('id')->on('client_portals')->nullOnDelete();
            });
        }

        Schema::create('studio_document_versions', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->unsignedSmallInteger('version');
            $table->json('snapshot');
            $table->longText('html_body');
            $table->string('pdf_disk', 40)->nullable();
            $table->string('pdf_path')->nullable();
            $table->string('change_summary')->nullable();
            $table->string('validation_code', 32);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->unique(['business_document_id', 'version']);
        });

        Schema::table('business_documents', function (Blueprint $table): void {
            $table->foreign('current_version_id')->references('id')->on('studio_document_versions')->nullOnDelete();
        });

        Schema::create('studio_document_shares', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->foreignUuid('document_version_id')->constrained('studio_document_versions')->cascadeOnDelete();
            $table->string('token_prefix', 12)->index();
            $table->string('token_hash', 64)->unique();
            $table->string('signature', 128);
            $table->timestamp('expires_at');
            $table->timestamp('revoked_at')->nullable();
            $table->timestamp('last_used_at')->nullable();
            $table->timestamps();
        });

        Schema::create('studio_document_views', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->foreignUuid('document_share_id')->nullable()->constrained('studio_document_shares')->nullOnDelete();
            $table->foreignUuid('document_version_id')->nullable()->constrained('studio_document_versions')->nullOnDelete();
            $table->string('ip', 45)->nullable();
            $table->string('user_agent', 512)->nullable();
            $table->string('device', 40)->nullable();
            $table->timestamp('started_at');
            $table->timestamp('ended_at')->nullable();
            $table->unsignedInteger('duration_seconds')->default(0);
            $table->timestamps();
            $table->index(['business_document_id', 'started_at']);
        });

        Schema::create('studio_document_decisions', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->foreignUuid('document_version_id')->constrained('studio_document_versions')->cascadeOnDelete();
            $table->string('decision', 40);
            $table->text('comment')->nullable();
            $table->string('decided_by_name')->nullable();
            $table->string('ip', 45)->nullable();
            $table->timestamp('created_at')->useCurrent();
        });

        Schema::create('studio_document_comments', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->foreignUuid('document_version_id')->nullable()->constrained('studio_document_versions')->nullOnDelete();
            $table->string('author_type', 20)->default('client');
            $table->foreignId('author_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('author_name')->nullable();
            $table->text('body');
            $table->boolean('visible_to_client')->default(true);
            $table->timestamps();
        });

        Schema::create('studio_document_histories', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->string('event', 60);
            $table->string('actor_type', 20)->default('system');
            $table->foreignId('actor_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->json('payload')->nullable();
            $table->string('message')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->index(['business_document_id', 'created_at']);
        });

        Schema::create('studio_document_attachments', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('business_document_id')->constrained('business_documents')->cascadeOnDelete();
            $table->string('disk', 40);
            $table->string('path');
            $table->string('original_name');
            $table->string('mime', 120)->nullable();
            $table->unsignedBigInteger('size')->default(0);
            $table->timestamps();
            $table->index(['business_document_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('studio_document_attachments');
        Schema::dropIfExists('studio_document_histories');
        Schema::dropIfExists('studio_document_comments');
        Schema::dropIfExists('studio_document_decisions');
        Schema::dropIfExists('studio_document_views');
        Schema::dropIfExists('studio_document_shares');
        Schema::table('business_documents', function (Blueprint $table): void {
            $table->dropForeign(['current_version_id']);
        });
        Schema::dropIfExists('studio_document_versions');
        Schema::dropIfExists('business_documents');
        Schema::dropIfExists('studio_document_templates');
    }
};
