<?php

namespace App\Libraries;

use App\Models\ApiTokenModel;

class TokenService
{
    private ApiTokenModel $model;

    public function __construct()
    {
        $this->model = new ApiTokenModel();
    }

    /** Generate a raw token, store its hash, and return the raw token. */
    public function issue(int $userId, int $churchId, bool $isPlatformAdmin = false, ?int $platformAdminId = null): string
    {
        $raw  = bin2hex(random_bytes(32)); // 64 hex chars
        $hash = hash('sha256', $raw);

        $this->model->insert([
            'user_id'            => $isPlatformAdmin ? null : $userId,
            'church_id'          => $isPlatformAdmin ? null : $churchId,
            'token_hash'         => $hash,
            'expires_at'         => date('Y-m-d H:i:s', strtotime('+30 days')),
            'last_used_at'       => date('Y-m-d H:i:s'),
            'is_platform_admin'  => $isPlatformAdmin ? 1 : 0,
            'platform_admin_id'  => $platformAdminId,
        ]);

        return $raw;
    }

    /** Look up a raw token; returns the token row or null. */
    public function validate(string $raw): ?array
    {
        $hash  = hash('sha256', $raw);
        $token = $this->model->findByHash($hash);

        if ($token) {
            $this->model->touch($token['id']);
        }

        return $token;
    }

    /** Revoke a specific raw token. */
    public function revoke(string $raw): void
    {
        $hash = hash('sha256', $raw);
        $this->model->where('token_hash', $hash)->delete();
    }

    /** Revoke by token row ID (used in refresh flow). */
    public function revokeById(int $id): void
    {
        $this->model->delete($id);
    }
}
