<?php

namespace App\Infrastructure\Repositories;

use App\Domain\Entities\User;
use App\Domain\Repositories\UserRepositoryInterface;
use App\Drivers\DatabaseDriver;
use PDO;

class MySqlUserRepository implements UserRepositoryInterface
{
    private PDO $db;

    public function __construct(DatabaseDriver $driver)
    {
        $this->db = $driver->getConnection();
    }

    public function findById(int $id): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM auth_users WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ? User::fromArray($row) : null;
    }

    public function findByEmail(string $email): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM auth_users WHERE email = :email LIMIT 1');
        $stmt->execute(['email' => $email]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ? User::fromArray($row) : null;
    }

    public function findByUsername(string $username): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM auth_users WHERE username = :username LIMIT 1');
        $stmt->execute(['username' => $username]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ? User::fromArray($row) : null;
    }

    public function create(User $user): User
    {
        $stmt = $this->db->prepare(
            'INSERT INTO auth_users (name, username, email, password, phone, address, role_id, status_id, created_at, updated_at)
             VALUES (:name, :username, :email, :password, :phone, :address, :role_id, :status_id, NOW(), NOW())'
        );
        $stmt->execute([
            'name' => $user->name,
            'username' => $user->username,
            'email' => $user->email,
            'password' => $user->password,
            'phone' => $user->phone,
            'address' => $user->address,
            'role_id' => $user->roleId,
            'status_id' => $user->statusId,
        ]);

        $user->id = (int)$this->db->lastInsertId();
        return $user;
    }

    public function updatePassword(int $id, string $passwordHash): void
    {
        $stmt = $this->db->prepare('UPDATE auth_users SET password = :password, updated_at = NOW() WHERE id = :id');
        $stmt->execute(['id' => $id, 'password' => $passwordHash]);
    }

    public function roles(): array
    {
        return $this->db->query('SELECT id, name, slug FROM auth_roles ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
    }

    public function statuses(): array
    {
        return $this->db->query('SELECT id, name, slug FROM auth_statuses ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
    }
}
