<?php

namespace App\Console\Commands;

use Database\Seeders\RolesAndPermissionsSeeder;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class CreateInitialAdmin extends Command
{
    protected $signature = 'app:create-initial-admin
        {--name= : Admin full name}
        {--email= : Admin email}
        {--password= : Admin password}
        {--from-env : Read credentials from INITIAL_ADMIN_* environment variables}';

    protected $description = 'Create the initial administrator account when no users exist';

    public function handle(): int
    {
        // Always ensure roles/permissions are present before assigning roles.
        Artisan::call('db:seed', ['--class' => RolesAndPermissionsSeeder::class, '--force' => true]);

        $name = (string) ($this->option('name') ?? '');
        $email = (string) ($this->option('email') ?? '');
        $password = (string) ($this->option('password') ?? '');

        if ($this->option('from-env')) {
            $name = (string) env('INITIAL_ADMIN_NAME', $name);
            $email = (string) env('INITIAL_ADMIN_EMAIL', $email);
            $password = (string) env('INITIAL_ADMIN_PASSWORD', $password);
        }

        if ($name === '' || $email === '' || $password === '') {
            if (! $this->input->isInteractive()) {
                $this->error('Missing initial admin credentials. Set INITIAL_ADMIN_NAME, INITIAL_ADMIN_EMAIL and INITIAL_ADMIN_PASSWORD.');
                return self::FAILURE;
            }

            $name = $name !== '' ? $name : $this->ask('Nome amministratore');
            $email = $email !== '' ? $email : $this->ask('Email amministratore');
            $password = $password !== '' ? $password : (string) $this->secret('Password amministratore (min 8 caratteri)');
        }

        if (User::count() > 0) {
            $existingAdmin = User::role('amministratore')->first();
            if ($existingAdmin) {
                $this->info('An administrator already exists. Skipping initial admin creation.');
                return self::SUCCESS;
            }

            if ($email !== '') {
                $existingUser = User::where('email', $email)->first();
                if ($existingUser) {
                    $existingUser->assignRole('amministratore');
                    $this->info("Granted admin role to existing user: {$existingUser->email}");
                    return self::SUCCESS;
                }
            }

            $firstUser = User::query()->oldest('id')->first();
            if ($firstUser) {
                $firstUser->assignRole('amministratore');
                $this->warn("No admin role found. Granted admin role to first existing user: {$firstUser->email}");
                return self::SUCCESS;
            }
        }

        $validator = Validator::make([
            'name' => $name,
            'email' => $email,
            'password' => $password,
        ], [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return self::FAILURE;
        }

        $admin = DB::transaction(function () use ($name, $email, $password) {
            $user = User::create([
                'name' => $name,
                'email' => $email,
                'password' => Hash::make($password),
            ]);

            $user->assignRole('amministratore');

            return $user;
        });

        $this->info("Initial admin created: {$admin->email}");

        return self::SUCCESS;
    }
}
