<?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
    {
        Schema::create('proposal_templates', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name');
            $table->string('purpose', 40)->default('sale'); // sale|rent|listing
            $table->longText('body_html');
            $table->boolean('is_default')->default(false);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->index(['tenant_id', 'purpose', 'is_default']);
        });

        Schema::create('proposals', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $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('template_id')->nullable()->constrained('proposal_templates')->nullOnDelete();
            $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->decimal('commission_percent', 5, 2)->nullable();
            $table->text('intro_message')->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', 'deal_id']);
        });

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

        Schema::create('proposal_versions', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->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(['proposal_id', 'version']);
        });

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

        Schema::create('proposal_recipients', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->cascadeOnDelete();
            $table->foreignUuid('contact_id')->nullable()->constrained('contacts')->nullOnDelete();
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('role', 40)->default('client');
            $table->timestamps();
        });

        Schema::create('proposal_shares', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->cascadeOnDelete();
            $table->foreignUuid('proposal_version_id')->constrained('proposal_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('proposal_views', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->cascadeOnDelete();
            $table->foreignUuid('proposal_share_id')->nullable()->constrained('proposal_shares')->nullOnDelete();
            $table->foreignUuid('proposal_version_id')->nullable()->constrained('proposal_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(['proposal_id', 'started_at']);
        });

        Schema::create('proposal_decisions', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->cascadeOnDelete();
            $table->foreignUuid('proposal_version_id')->constrained('proposal_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('proposal_comments', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->cascadeOnDelete();
            $table->foreignUuid('proposal_version_id')->nullable()->constrained('proposal_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('proposal_histories', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('proposal_id')->constrained('proposals')->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(['proposal_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('proposal_histories');
        Schema::dropIfExists('proposal_comments');
        Schema::dropIfExists('proposal_decisions');
        Schema::dropIfExists('proposal_views');
        Schema::dropIfExists('proposal_shares');
        Schema::dropIfExists('proposal_recipients');
        Schema::table('proposals', function (Blueprint $table): void {
            $table->dropForeign(['current_version_id']);
        });
        Schema::dropIfExists('proposal_versions');
        Schema::dropIfExists('proposals');
        Schema::dropIfExists('proposal_templates');
    }
};
