<?php

declare(strict_types=1);

namespace App\Models;

class UserInvitation extends BaseModel
{
    protected string $table = 'user_invitations';
    protected string $primaryKey = 'id';

    public function createInvitation(string $email, string $token, string $role, int $invitedBy, int $expiresIn = 86400): int
    {
        $this->execute(
            "INSERT INTO {$this->table} (email, token, role, invited_by, status, expires_at)
             VALUES (:email, :token, :role, :invited_by, 'pendiente', DATE_ADD(NOW(), INTERVAL :seconds SECOND))",
            [
                'email' => $email,
                'token' => $token,
                'role' => $role,
                'invited_by' => $invitedBy,
                'seconds' => $expiresIn,
            ]
        );

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

    public function findByToken(string $token): ?array
    {
        return $this->queryOne(
            "SELECT * FROM {$this->table} WHERE token = :token AND status = 'pendiente' AND expires_at > NOW() LIMIT 1",
            ['token' => $token]
        );
    }

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

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

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

    public function invalidateExistingForEmail(string $email): void
    {
        $this->execute(
            "UPDATE {$this->table} SET status = 'expirada' WHERE email = :email AND status = 'pendiente'",
            ['email' => $email]
        );
    }

    public function cleanExpired(): void
    {
        $this->execute(
            "UPDATE {$this->table} SET status = 'expirada' WHERE status = 'pendiente' AND expires_at < NOW()"
        );
    }
}
