<?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::create('integration_settings', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('business_id');
            $table->string('provider', 30);
            $table->text('credentials')->nullable();
            $table->json('configuration')->nullable();
            $table->boolean('enabled')->default(false);
            $table->timestamp('last_synced_at')->nullable();
            $table->text('last_error')->nullable();
            $table->timestamps();
            $table->unique(['business_id', 'provider']);
        });

        Schema::create('integration_links', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('business_id');
            $table->string('provider', 30);
            $table->string('entity_type', 40);
            $table->unsignedBigInteger('entity_id');
            $table->string('external_id');
            $table->string('external_status')->nullable();
            $table->json('metadata')->nullable();
            $table->timestamps();
            $table->unique(['business_id', 'provider', 'entity_type', 'external_id'], 'integration_external_unique');
            $table->index(['business_id', 'provider', 'entity_type', 'entity_id'], 'integration_entity_index');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('integration_links');
        Schema::dropIfExists('integration_settings');
    }
};
