<?php

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

return new class extends Migration {
    public function up(): void
    {
        Schema::create('account_contact', function (Blueprint $table) {
            $table->id();
            $table->foreignId('account_id')->index();
            $table->foreignId('contact_id')->index();
            $table->boolean('is_primary')->default(false);
            $table->string('role')->nullable();
            $table->timestamps();
            $table->unique(['account_id', 'contact_id']);
        });

        Schema::create('contact_project', function (Blueprint $table) {
            $table->id();
            $table->foreignId('contact_id')->index();
            $table->foreignId('project_id')->index();
            $table->timestamps();
            $table->unique(['contact_id', 'project_id']);
        });

        Schema::create('contact_product', function (Blueprint $table) {
            $table->id();
            $table->foreignId('contact_id')->index();
            $table->foreignId('product_id')->index();
            $table->timestamps();
            $table->unique(['contact_id', 'product_id']);
        });

        Schema::create('contact_survey', function (Blueprint $table) {
            $table->id();
            $table->foreignId('contact_id')->index();
            $table->foreignId('survey_id')->index();
            $table->timestamps();
            $table->unique(['contact_id', 'survey_id']);
        });

        Schema::create('contact_move_histories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('business_id')->index();
            $table->foreignId('contact_id')->index();
            $table->string('destination_type');
            $table->unsignedBigInteger('destination_id');
            $table->foreignId('moved_by')->nullable()->index();
            $table->text('reason')->nullable();
            $table->json('relationship_snapshot')->nullable();
            $table->timestamps();
            $table->index(['destination_type', 'destination_id']);
        });

        DB::table('accounts')->whereNotNull('primary_contact_id')->orderBy('id')->each(function ($account) {
            DB::table('account_contact')->insertOrIgnore([
                'account_id' => $account->id,
                'contact_id' => $account->primary_contact_id,
                'is_primary' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('contact_move_histories');
        Schema::dropIfExists('contact_survey');
        Schema::dropIfExists('contact_product');
        Schema::dropIfExists('contact_project');
        Schema::dropIfExists('account_contact');
    }
};
