<?php
declare(strict_types=1);

namespace App\Modules\Auth\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Users\Models\Employee;

final class TokenController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function store(Request $request): Response
    {
        $data = $this->validatedJson([
            'username' => 'required|string',
            'password' => 'required|string',
            'token_name' => 'nullable|string|max:100',
        ]);

        $db = App::getInstance()->db();
        $employee = $db->selectOne(
            "SELECT id, password_hash, is_active FROM employees WHERE username = ?",
            [$data['username']]
        );

        if (!$employee || !password_verify($data['password'], $employee['password_hash'])) {
            return $this->errorResponse('بيانات الدخول غير صحيحة', 401);
        }

        if (!$employee['is_active']) {
            return $this->errorResponse('الحساب غير نشط', 401);
        }

        $config = App::getInstance()->config('api.token', []);
        $maxTokens = $config['max_per_employee'] ?? 5;

        $activeCount = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM api_tokens WHERE employee_id = ? AND is_revoked = 0 AND (expires_at IS NULL OR expires_at > NOW())",
            [$employee['id']]
        );

        if (($activeCount['cnt'] ?? 0) >= $maxTokens) {
            return $this->errorResponse('تم الوصول للحد الأقصى من التوكنات النشطة', 422);
        }

        $token = bin2hex(random_bytes(32));
        $ttlHours = $config['ttl_hours'] ?? 720;
        $expiresAt = date('Y-m-d H:i:s', time() + ($ttlHours * 3600));
        $tokenName = $data['token_name'] ?? 'default';

        $db->insert('api_tokens', [
            'employee_id' => $employee['id'],
            'token' => $token,
            'name' => $tokenName,
            'expires_at' => $expiresAt,
        ]);

        return $this->successResponse([
            'token' => $token,
            'name' => $tokenName,
            'expires_at' => $expiresAt,
        ], 201);
    }

    public function index(Request $request): Response
    {
        $employee = App::getInstance()->currentEmployee();
        $db = App::getInstance()->db();

        $tokens = $db->select(
            "SELECT id, name, last_used_at, expires_at, created_at FROM api_tokens WHERE employee_id = ? AND is_revoked = 0 ORDER BY created_at DESC",
            [$employee->id]
        );

        return $this->successResponse($tokens);
    }

    public function revoke(Request $request, string $id): Response
    {
        $employee = App::getInstance()->currentEmployee();
        $db = App::getInstance()->db();

        $token = $db->selectOne(
            "SELECT id FROM api_tokens WHERE id = ? AND employee_id = ? AND is_revoked = 0",
            [(int) $id, $employee->id]
        );

        if (!$token) {
            return $this->errorResponse('التوكن غير موجود', 404);
        }

        $db->update('api_tokens', ['is_revoked' => 1], 'id = ?', [(int) $id]);

        return $this->successResponse(['revoked' => true]);
    }
}
