<?php

namespace Database\Seeders;

use App\Domains\AI\Actions\CreateDefaultAiSettingsAction;
use App\Domains\Billing\Models\Plan;
use App\Domains\Billing\Models\Subscription;
use App\Domains\Identity\Actions\CreateDefaultRolesAction;
use App\Domains\Leads\Actions\CreateDefaultPipelineAction;
use App\Domains\Tenancy\Models\Branch;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Seeds a platform operator (super admin) user for local/testing.
 * This user can access /admin pages when their email is listed in OPERATOR_EMAILS.
 *
 * Run: php artisan db:seed --class=OperatorUserSeeder
 *
 * Then add the same email to .env: OPERATOR_EMAILS=superadmin@chatsell.local
 */
class OperatorUserSeeder extends Seeder
{
    public const DEFAULT_EMAIL = 'superadmin@chatsell.local';

    public const DEFAULT_PASSWORD = 'SuperAdmin123!';

    public function run(): void
    {
        $email = strtolower((string) env('SUPERADMIN_EMAIL', self::DEFAULT_EMAIL));
        $password = env('SUPERADMIN_PASSWORD', self::DEFAULT_PASSWORD);

        $existing = User::query()->where('email', $email)->first();
        if ($existing) {
            $this->command->info("Operator user already exists: {$email}. Skipping. Add this email to OPERATOR_EMAILS in .env to access /admin.");

            return;
        }

        $plan = Plan::query()->where('slug', 'starter')->first();
        if (! $plan) {
            $this->command->warn('Run PlanSeeder first: php artisan db:seed --class=PlanSeeder');

            return;
        }

        if (\Spatie\Permission\Models\Permission::query()->count() === 0) {
            $this->command->warn('Run PermissionSeeder first: php artisan db:seed --class=PermissionSeeder');

            return;
        }

        DB::transaction(function () use ($email, $password, $plan) {
            $tenant = Tenant::query()->create([
                'company_name' => 'Platform Operator',
                'slug' => 'platform-operator-'.Str::random(6),
                'country_code' => null,
                'currency_code' => 'USD',
                'timezone' => 'UTC',
                'status' => 'trial',
                'plan_id' => $plan->getKey(),
                'trial_ends_at' => now()->addYear(),
                'onboarding_completed_at' => now(),
            ]);

            $branch = Branch::query()->create([
                'tenant_id' => $tenant->getKey(),
                'name' => 'Main',
                'code' => 'MAIN',
                'phone' => null,
                'is_active' => true,
            ]);

            $user = User::query()->create([
                'tenant_id' => $tenant->getKey(),
                'branch_id' => $branch->getKey(),
                'full_name' => 'Super Admin',
                'email' => $email,
                'phone' => null,
                'status' => 'active',
            ]);
            $user->password = $password;
            $user->save();

            Subscription::query()->create([
                'tenant_id' => $tenant->getKey(),
                'plan_id' => $plan->getKey(),
                'status' => 'trial',
                'starts_at' => now(),
                'trial_ends_at' => $tenant->trial_ends_at,
            ]);

            app(CreateDefaultRolesAction::class)->execute($tenant, $user);
            app(CreateDefaultPipelineAction::class)->execute($tenant);
            app(CreateDefaultAiSettingsAction::class)->execute($tenant);
        });

        $this->command->info('Operator user created.');
        $this->command->line("  Email:    {$email}");
        $this->command->line('  Password: '.($password === self::DEFAULT_PASSWORD ? self::DEFAULT_PASSWORD : '(from SUPERADMIN_PASSWORD)'));
        $this->command->line('');
        $this->command->line('Add to .env: OPERATOR_EMAILS='.$email);
        $this->command->line('Then log in at /login and open /admin to access super admin pages.');
    }
}
