<?php
declare(strict_types=1);

namespace App\Support;

use App\Core\Database;
use PDO;
use Throwable;

final class AdminUserStore
{
    private ?PDO $pdo;

    public function __construct()
    {
        $this->pdo = (new Database())->connection();
    }

    public function findByEmail(string $email): ?array
    {
        if ($this->pdo instanceof PDO) {
            try {
                $this->seedDefaults();

                $statement = $this->pdo->prepare(
                    'SELECT admin_users.full_name, admin_users.email, admin_users.password_hash
                     FROM admin_users
                     INNER JOIN admin_roles ON admin_roles.id = admin_users.role_id
                     WHERE admin_users.email = :email AND admin_users.is_active = 1
                     LIMIT 1'
                );
                $statement->execute(['email' => $email]);
                $user = $statement->fetch();

                if (is_array($user)) {
                    return [
                        'name' => $user['full_name'],
                        'email' => $user['email'],
                        'password_hash' => $user['password_hash'],
                    ];
                }
            } catch (Throwable) {
            }
        }

        foreach ((array) config('admin_users', []) as $adminUser) {
            if ($email === (string) $adminUser['email']) {
                return $adminUser;
            }
        }

        return null;
    }

    public function create(string $fullName, string $email, string $password): int
    {
        if (!$this->pdo instanceof PDO) {
            throw new \RuntimeException('Database connection is required to create administrator accounts.');
        }

        $this->seedDefaults();

        $statement = $this->pdo->prepare(
            'INSERT INTO admin_users (role_id, full_name, email, password_hash, is_active)
             VALUES (1, :full_name, :email, :password_hash, 1)'
        );
        $statement->execute([
            'full_name' => $fullName,
            'email' => $email,
            'password_hash' => password_hash($password, PASSWORD_DEFAULT),
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    public function existsByEmail(string $email): bool
    {
        return $this->findByEmail($email) !== null;
    }

    private function seedDefaults(): void
    {
        if (!$this->pdo instanceof PDO) {
            return;
        }

        $this->pdo->exec("INSERT IGNORE INTO admin_roles (id, name) VALUES (1, 'System Administrator')");

        $statement = $this->pdo->prepare(
            'INSERT INTO admin_users (role_id, full_name, email, password_hash, is_active)
             VALUES (1, :full_name, :email, :password_hash, 1)
             ON DUPLICATE KEY UPDATE full_name = admin_users.full_name'
        );

        foreach ((array) config('admin_users', []) as $adminUser) {
            $statement->execute([
                'full_name' => $adminUser['name'],
                'email' => $adminUser['email'],
                'password_hash' => $adminUser['password_hash'],
            ]);
        }
    }
}