<?php

namespace App\Console\Commands;

use App\Models\Event;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Console\Attributes\AsCommand;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[AsCommand(name: 'tenant:attach-demo-event')]
class AttachDemoEvent extends Command
{
    protected $signature = 'tenant:attach-demo-event
        {--tenant-email=demo@example.com : Email of tenant admin user to locate tenant}
        {--tenant-slug= : Tenant slug (overrides tenant-email lookup)}
        {--event-id= : Event ID}
        {--event-slug= : Event slug}
    ';

    protected $description = 'Attach an existing demo event to a tenant (by email or slug). Safe and idempotent.';

    public function handle(): int
    {
        if (! \Illuminate\Support\Facades\Schema::hasTable('events')) {
            $this->error("Table 'events' does not exist. Run: php artisan migrate");
            return self::FAILURE;
        }
        if (! \Illuminate\Support\Facades\Schema::hasColumn('events', 'tenant_id')) {
            $this->error("Column 'events.tenant_id' does not exist. Add it and rerun. Suggested: create a migration to add a nullable foreignId to tenants.");
            return self::FAILURE;
        }
        $tenant = null;
        if ($slug = $this->option('tenant-slug')) {
            $tenant = Tenant::where('slug', $slug)->first();
        }
        if (! $tenant) {
            $email = (string) $this->option('tenant-email');
            /** @var User|null $user */
            $user = User::where('email', $email)->first();
            if ($user && $user->tenant_id) {
                $tenant = Tenant::find($user->tenant_id);
            }
        }
        if (! $tenant) {
            $this->error('Tenant not found. Provide --tenant-slug or a user with tenant_id via --tenant-email.');
            return self::FAILURE;
        }

        $event = null;
        if ($id = $this->option('event-id')) {
            $event = Event::find($id);
        } elseif ($slug = $this->option('event-slug')) {
            $event = Event::where('slug', $slug)->first();
        } else {
            // Heuristics: first event without tenant, or a demo wedding by slug/name
            $event = Event::whereNull('tenant_id')->first();
            if (! $event) {
                $event = Event::where('slug', 'like', '%demo%')->where('slug', 'like', '%wedding%')->first();
            }
            if (! $event) {
                // Try JSON name contains "Demo" or "Wedding"
                $event = Event::where('name', 'like', '%Demo%')->orWhere('name', 'like', '%Wedding%')->first();
            }
        }

        if (! $event) {
            $this->error('Event not found. Provide --event-id or --event-slug.');
            return self::FAILURE;
        }

        // Idempotent update
        if ((int) $event->tenant_id === (int) $tenant->id) {
            $this->info("Event #{$event->id} already attached to tenant #{$tenant->id} ({$tenant->slug}).");
            return self::SUCCESS;
        }

        $event->tenant_id = $tenant->id;
        $event->save();

        $this->info("Attached event #{$event->id} ({$event->slug}) to tenant #{$tenant->id} ({$tenant->slug}).");
        return self::SUCCESS;
    }
}
