<?php

namespace App\Services;

class ApiTokenService
{
    public function issue(int $userId,string $name='mobile',int $days=30): string
    {
        $token=bin2hex(random_bytes(32));
        db_connect()->table('api_tokens')->insert(['user_id'=>$userId,'name'=>$name,'token_hash'=>hash('sha256',$token),'expires_at'=>date('Y-m-d H:i:s',time()+86400*$days),'created_at'=>date('Y-m-d H:i:s')]);
        return $token;
    }
    public function authenticate(string $token): ?array
    {
        if(strlen($token)<32)return null; $db=db_connect();
        $row=$db->table('api_tokens t')->select('t.id token_id,t.user_id,t.expires_at,t.revoked_at,u.full_name,u.email,u.role,u.avatar,u.status')->join('users u','u.id=t.user_id')->where('t.token_hash',hash('sha256',$token))->get()->getRowArray();
        if(!$row || $row['status']!=='active' || $row['revoked_at'] || ($row['expires_at'] && strtotime($row['expires_at'])<time()))return null;
        $db->table('api_tokens')->where('id',$row['token_id'])->update(['last_used_at'=>date('Y-m-d H:i:s')]);
        return ['id'=>(int)$row['user_id'],'full_name'=>$row['full_name'],'email'=>$row['email'],'role'=>$row['role'],'avatar'=>$row['avatar'],'token_id'=>(int)$row['token_id']];
    }
    public function revoke(int $tokenId): void { db_connect()->table('api_tokens')->where('id',$tokenId)->update(['revoked_at'=>date('Y-m-d H:i:s')]); }
}
