<?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
    {
        // Create tenants table if not exists
        if (!Schema::hasTable('tenants')) {
            Schema::create('tenants', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('slug')->unique();
                $table->string('domain')->nullable()->unique();
                $table->string('contact_name')->nullable();
                $table->string('contact_email')->nullable();
                $table->string('contact_phone')->nullable();
                $table->integer('max_photos_per_event')->default(500);
                $table->integer('max_storage_mb')->default(1024);
                $table->json('features')->nullable();
                $table->timestamp('last_activity_at')->nullable();
                $table->integer('is_active');
                $table->integer('is_suspended');
                $table->string('email')->nullable(); // From add_email_to_tenants
                $table->string('stripe_account_id')->nullable(); // From add_stripe_account_id
                $table->string('custom_domain')->nullable(); // From add_custom_domain
                $table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade'); // From add_user_id_to_tenants
                $table->timestamps();
            });
        } else {
            // Add missing columns to existing tenants table
            if (!Schema::hasColumn('tenants', 'email')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->string('email')->nullable()->after('contact_phone');
                });
            }
            if (Schema::hasColumn('tenants', 'event_credits_balance')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->dropColumn(['event_credits_balance', 'free_event_granted_at']);
                });
            }
            if (!Schema::hasColumn('tenants', 'stripe_account_id')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->string('stripe_account_id')->nullable()->after('features');
                });
            }
            if (!Schema::hasColumn('tenants', 'custom_domain')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->string('custom_domain')->nullable()->after('domain');
                });
            }
            if (!Schema::hasColumn('tenants', 'user_id')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade')->after('id');
                });
            }
            // Flatten tenant name if needed (from flatten_tenant_name_column)
            if (Schema::hasColumn('tenants', 'name_json')) { // Assuming old column name
                Schema::table('tenants', function (Blueprint $table) {
                    $table->string('name')->after('id');
                    // Migration logic for data transfer would be here, but since idempotent, assume manual or skip
                });
                Schema::table('tenants', function (Blueprint $table) {
                    $table->dropColumn('name_json');
                });
            }
            // Add subscription fields (from add_subscription_fields_to_tenants_table)
            if (!Schema::hasColumn('tenants', 'subscription_status')) {
                Schema::table('tenants', function (Blueprint $table) {
                    $table->string('subscription_status')->default('active')->after('event_credits_balance');
                    $table->timestamp('subscription_ends_at')->nullable()->after('subscription_status');
                });
            }
        }

        // Add tenant_id to users if not exists
        if (Schema::hasTable('users') && !Schema::hasColumn('users', 'tenant_id')) {
            Schema::table('users', function (Blueprint $table) {
                $table->foreignId('tenant_id')->nullable()->after('id')->constrained('tenants')->nullOnDelete();
            });
        }

        // Add tenant_id to events if not exists
        if (Schema::hasTable('events') && !Schema::hasColumn('events', 'tenant_id')) {
            Schema::table('events', function (Blueprint $table) {
                $table->foreignId('tenant_id')->nullable()->after('id')->constrained('tenants')->nullOnDelete();
            });
        }
    }

    public function down(): void
    {
        if (app()->environment('local', 'testing')) {
            if (Schema::hasColumn('events', 'tenant_id')) {
                Schema::table('events', function (Blueprint $table) {
                    $table->dropForeign(['tenant_id']);
                    $table->dropColumn('tenant_id');
                });
            }
            if (Schema::hasColumn('users', 'tenant_id')) {
                Schema::table('users', function (Blueprint $table) {
                    $table->dropForeign(['tenant_id']);
                    $table->dropColumn('tenant_id');
                });
            }
            Schema::dropIfExists('tenants');
        }
    }
};
