<?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('integration_settings', function (Blueprint $table) {
            $table->string('health_status')->default('unknown')->after('enabled');
            $table->timestamp('last_health_checked_at')->nullable()->after('last_synced_at');
            $table->timestamp('credentials_expires_at')->nullable()->after('last_health_checked_at');
            $table->timestamp('last_refreshed_at')->nullable()->after('credentials_expires_at');
            $table->text('refresh_error')->nullable()->after('last_error');
        });
        Schema::table('integration_sync_logs', function (Blueprint $table) {
            $table->string('idempotency_key', 64)->nullable()->after('external_id');
            $table->unsignedInteger('max_attempts')->default(5)->after('attempts');
            $table->dateTime('next_retry_at')->nullable()->after('max_attempts');
            $table->index(['status', 'next_retry_at']);
            $table->unique(['business_id','provider','idempotency_key'], 'integration_webhook_replay_unique');
        });
        Schema::create('integration_field_mappings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('business_id')->index();
            $table->string('provider');
            $table->string('entity_type');
            $table->string('external_field');
            $table->string('crm_field');
            $table->json('value_map')->nullable();
            $table->boolean('enabled')->default(true);
            $table->timestamps();
            $table->unique(['business_id','provider','entity_type','external_field'], 'integration_mapping_unique');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('integration_field_mappings');
        Schema::table('integration_sync_logs', function (Blueprint $table) {
            $table->dropUnique('integration_webhook_replay_unique');
            $table->dropIndex(['status','next_retry_at']);
            $table->dropColumn(['idempotency_key','max_attempts','next_retry_at']);
        });
        Schema::table('integration_settings', function (Blueprint $table) {
            $table->dropColumn(['health_status','last_health_checked_at','credentials_expires_at','last_refreshed_at','refresh_error']);
        });
    }
};
