<?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
    {
        if (! Schema::hasTable('customers')) {
            Schema::create('customers', function (Blueprint $table) {
                $table->id();
                $table->string('public_id', 40)->unique();
                $table->foreignId('merchant_id')->constrained()->cascadeOnDelete();
                $table->string('environment', 16);
                $table->string('reference_id', 100)->nullable();
                $table->string('name')->nullable();
                $table->string('email')->nullable();
                $table->string('phone', 40)->nullable();
                $table->string('status', 20)->default('active')->index();
                $table->json('billing_address')->nullable();
                $table->json('shipping_address')->nullable();
                $table->json('metadata')->nullable();
                $table->timestamp('archived_at')->nullable();
                $table->timestamps();
                $table->index(['merchant_id', 'environment', 'status']);
                $table->unique(['merchant_id', 'environment', 'reference_id']);
                $table->unique(['merchant_id', 'environment', 'email']);
            });
        }

        if (Schema::hasTable('invoices') && ! Schema::hasColumn('invoices', 'customer_id')) {
            Schema::table('invoices', function (Blueprint $table) {
                $table->foreignId('customer_id')->nullable()->after('sub_merchant_id')->constrained('customers')->nullOnDelete();
            });
        }

        if (Schema::hasTable('subscriptions') && ! Schema::hasColumn('subscriptions', 'customer_id')) {
            Schema::table('subscriptions', function (Blueprint $table) {
                $table->foreignId('customer_id')->nullable()->after('subscription_plan_id')->constrained('customers')->nullOnDelete();
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('subscriptions') && Schema::hasColumn('subscriptions', 'customer_id')) {
            Schema::table('subscriptions', function (Blueprint $table) {
                $table->dropConstrainedForeignId('customer_id');
            });
        }

        if (Schema::hasTable('invoices') && Schema::hasColumn('invoices', 'customer_id')) {
            Schema::table('invoices', function (Blueprint $table) {
                $table->dropConstrainedForeignId('customer_id');
            });
        }

        Schema::dropIfExists('customers');
    }
};
