<?php

namespace App\Console\Commands;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Console\Attributes\AsCommand;

#[AsCommand(name: 'tenant:add-dummy')]
class AddDummyTenantUser extends Command
{
    protected $signature = 'tenant:add-dummy
        {--email=demo@example.com}
        {--password=secret123!}
        {--tenant="Demo Tenant"}
        {--name="Demo Admin"}
        {--update-password : Overwrite password if user already exists}
    ';
    protected $description = 'Create a demo tenant and a tenant user with given credentials.';

    public function handle(): int
    {
        $email = (string) $this->option('email');
        $password = (string) $this->option('password');
        $tenantName = (string) $this->option('tenant');
        $userName = (string) $this->option('name');

        // Pre-flight checks for common failures
        if (! Schema::hasTable('users')) {
            $this->error("Table 'users' does not exist. Run: php artisan migrate");
            return self::FAILURE;
        }
        if (! Schema::hasTable('tenants')) {
            $this->error("Table 'tenants' does not exist. Run: php artisan migrate");
            return self::FAILURE;
        }

        DB::beginTransaction();
        try {
            // Create or fetch tenant
            $slug = Str::slug($tenantName ?: 'demo-tenant');
            /** @var Tenant $tenant */
            $tenant = Tenant::query()->where('slug', $slug)->first();
            if (! $tenant) {
                $tenant = new Tenant();
                $tenant->name = $tenantName;
                $tenant->slug = $slug;
                $tenant->domain = null;
                $tenant->contact_name = $userName;
                $tenant->contact_email = $email;
                $tenant->contact_phone = null;
                $tenant->event_credits_balance = 1;
                $tenant->max_photos_per_event = 500;
                $tenant->max_storage_mb = 1024;
                $tenant->features = ['custom_branding' => false];
                $tenant->save();
            }

            // Create or fetch user
            /** @var User $user */
            $user = User::query()->where('email', $email)->first();
            $updatePassword = (bool) $this->option('update-password');
            if (! $user) {
                $user = new User();
                if (Schema::hasColumn($user->getTable(), 'name')) $user->name = $userName;
                $user->email = $email;
                $user->password = Hash::make($password);
            } else if ($updatePassword) {
                $user->password = Hash::make($password);
            }
            if (Schema::hasColumn($user->getTable(), 'tenant_id')) {
                $user->tenant_id = $tenant->id;
            }
            if (Schema::hasColumn($user->getTable(), 'role')) {
                $user->role = 'tenant_admin';
            }
            $user->save();

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            $this->error('Failed: '.$e->getMessage());
            return self::FAILURE;
        }

        $this->info('Dummy tenant user created/updated.');
        $this->line('Tenant: '.$tenant->name.' (#'.$tenant->id.')');
        $this->line('Email: '.$email);
        $this->line('Password: '.$password);
        return self::SUCCESS;
    }
}
