<?php

namespace App\Console\Commands;

use App\Domain\Identity\Models\Role;
use App\Domain\Shared\Models\Academy;
use App\Models\User;
use Database\Seeders\FinancialAccountsSeeder;
use Database\Seeders\NotificationTemplateSeeder;
use Database\Seeders\PaymentNotificationTemplateSeeder;
use Database\Seeders\PermissionSeeder;
use Database\Seeders\RolesAndPermissionsSeeder;
use Database\Seeders\SystemSettingsSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SetupFreshInstall extends Command
{
    protected $signature = 'el-captain:setup {--no-interaction}';

    protected $description = 'First-time setup: create academy, admin user, and seed reference data';

    public function handle(): int
    {
        if (Academy::count() > 0) {
            $this->warn('Academy already exists. Skipping setup.');
            return self::SUCCESS;
        }

        $this->info('Setting up El Captain for first use...');

        $academyNameAr = env('ACADEMY_NAME_AR', 'أكاديمية الكابتن');
        $academyNameEn = env('ACADEMY_NAME_EN', 'El Captain Academy');
        $adminEmail = env('ADMIN_EMAIL', 'admin@example.com');
        $adminPassword = env('ADMIN_PASSWORD', 'password123');
        $adminName = env('ADMIN_NAME', 'مدير النظام');

        $slug = Str::slug($academyNameEn);

        $academy = Academy::create([
            'name' => $academyNameEn,
            'name_ar' => $academyNameAr,
            'slug' => $slug,
            'email' => $adminEmail,
            'currency' => 'EGP',
            'timezone' => 'Africa/Cairo',
            'locale' => 'ar',
            'status' => 'active',
        ]);

        $this->info("Academy created: {$academyNameAr}");

        app()->instance('current_academy', $academy);

        $admin = User::create([
            'academy_id' => $academy->id,
            'name' => $adminName,
            'name_ar' => $adminName,
            'email' => $adminEmail,
            'password' => Hash::make($adminPassword),
            'status' => 'active',
            'is_super_admin' => true,
        ]);

        $this->info("Admin user created: {$adminEmail}");

        $this->call('db:seed', ['--class' => FinancialAccountsSeeder::class, '--force' => true]);
        $this->call('db:seed', ['--class' => RolesAndPermissionsSeeder::class, '--force' => true]);
        $this->call('db:seed', ['--class' => PermissionSeeder::class, '--force' => true]);
        $this->call('db:seed', ['--class' => SystemSettingsSeeder::class, '--force' => true]);
        $this->call('db:seed', ['--class' => PaymentNotificationTemplateSeeder::class, '--force' => true]);

        if (class_exists(NotificationTemplateSeeder::class)) {
            $this->call('db:seed', ['--class' => NotificationTemplateSeeder::class, '--force' => true]);
        }

        $ownerRole = Role::where('academy_id', $academy->id)
            ->where('slug', 'academy_owner')
            ->first();

        if ($ownerRole) {
            $admin->update(['role_id' => $ownerRole->id]);
            $admin->roles()->syncWithoutDetaching([$ownerRole->id]);
        }

        $this->info('Roles, permissions, and settings seeded.');
        $this->newLine();
        $this->components->info("Setup complete! Log in at your app URL with: {$adminEmail}");

        return self::SUCCESS;
    }
}
