<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

/**
 * Creates or promotes a studio admin.
 *
 * Exists because there is no self-service route into the admin panel and
 * there should not be: the role column defaults to artist, so a fresh
 * install has nobody who can log in until someone runs this on the server.
 */
class MakeAdmin extends Command
{
    protected $signature = 'studio:make-admin
        {email : The account to create or promote}
        {--name= : Display name, when creating}';

    protected $description = 'Create a studio admin, or promote an existing account';

    public function handle(): int
    {
        $email = (string) $this->argument('email');

        if (Validator::make(['email' => $email], ['email' => 'required|email'])->fails()) {
            $this->error('That is not a valid email address.');

            return self::FAILURE;
        }

        $user = User::where('email', $email)->first();

        if ($user) {
            $user->update(['role' => UserRole::Admin]);

            $this->info("Promoted {$email} to studio admin.");

            return self::SUCCESS;
        }

        $password = $this->secret('Choose a password');

        $validator = Validator::make(
            ['password' => $password],
            ['password' => ['required', Password::min(12)->letters()->numbers()]],
        );

        if ($validator->fails()) {
            $this->error($validator->errors()->first('password'));

            return self::FAILURE;
        }

        if ($password !== $this->secret('Confirm password')) {
            $this->error('Passwords did not match.');

            return self::FAILURE;
        }

        User::create([
            'name' => $this->option('name') ?: str($email)->before('@')->headline()->value(),
            'email' => $email,
            'password' => Hash::make($password),
            'role' => UserRole::Admin,
        ])->forceFill(['email_verified_at' => now()])->save();

        $this->info("Created studio admin {$email}.");

        return self::SUCCESS;
    }
}
