<?php

declare(strict_types=1);

namespace App\Models;

class User extends BaseModel
{
    protected string $table = 'users';
    protected string $primaryKey = 'id';

    public function findByEmail(string $email): ?array
    {
        return $this->queryOne(
            "SELECT * FROM {$this->table} WHERE email = :email LIMIT 1",
            ['email' => $email]
        );
    }

    public function findByEmailOrFail(string $email): array
    {
        $user = $this->findByEmail($email);
        if (!$user) {
            throw new \RuntimeException('Usuario no encontrado', 404);
        }
        return $user;
    }

    public function createUser(array $data): int
    {
        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        return $this->create($data);
    }

    public function updatePassword(int $id, string $newPassword): bool
    {
        $hash = password_hash($newPassword, PASSWORD_BCRYPT);
        return $this->update($id, ['password' => $hash]);
    }

    public function activateUser(int $id): bool
    {
        return $this->update($id, ['status' => 'active']);
    }

    public function verifyPassword(array $user, string $password): bool
    {
        return password_verify($password, $user['password']);
    }

    public function setCurrentEvent(int $userId, int $eventId): bool
    {
        return $this->update($userId, ['current_event_id' => $eventId]);
    }
}
