<?php

namespace api\modules\v1\controllers;

use api\components\Controller;
use Yii;
use yii\web\UnauthorizedHttpException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use OpenApi\Annotations as OA; // แทน Attributes

/**
 * @OA\Tag(
 *   name="Auth",
 *   description="Authentication endpoints"
 * )
 */
class AuthController extends Controller
{
    public function behaviors()
    {
        $b = parent::behaviors();
        if (isset($b['authenticator'])) {
            $b['authenticator']['except'] = array_merge(
                $b['authenticator']['except'] ?? [],
                ['check'] // action id
            );
        }
        return $b;
    }

    /**
     * @OA\Get(
     *   path="/auth/me",
     *   summary="Get current user (requires Bearer token)",
     *   operationId="authMe",
     *   tags={"Auth"},
     *   security={{"bearerAuth": {}}},
     *   @OA\Response(
     *     response=200,
     *     description="User profile",
     *     @OA\JsonContent(ref="#/components/schemas/User")
     *   ),
     *   @OA\Response(
     *     response=401,
     *     description="Unauthorized",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="name", type="string", example="Unauthorized"),
     *       @OA\Property(property="message", type="string", example="Your request was made with invalid credentials."),
     *       @OA\Property(property="statusCode", type="integer", example=401)
     *     )
     *   )
     * )
     */
    public function actionMe()
    {
        //return 'test';
        $user = Yii::$app->user->identity;
        if (!$user) {
            throw new UnauthorizedHttpException('Unauthorized');
        }
        return $this->apiItem($user);
    }


    /**
     * @OA\Post(
     *   path="/auth/check",
     *   tags={"Auth"},
     *   summary="Check JWT is active (not expired)",
     *   operationId="authCheck",
     *   requestBody={"$ref":"#/components/requestBodies/AuthCheckBody"},
     *   @OA\Response(
     *     response=200,
     *     description="OK",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="active", type="boolean", example=true),
     *       @OA\Property(property="exp", type="integer", nullable=true, example=1723659999)
     *     )
     *   )
     * )
     */
    public function actionCheck()
    {
        $body = Yii::$app->request->getBodyParams();
        $jwt = $body['token'] ?? null;

        // รองรับ Authorization: Bearer ... ด้วย
        if (!$jwt) {
            $auth = Yii::$app->request->headers->get('Authorization');
            if ($auth && preg_match('/^Bearer\s+(.+)$/i', $auth, $m)) {
                $jwt = $m[1];
            }
        }

        if (!$jwt) {
            return $this->apiItem(['active' => false, 'exp' => null]);
        }

        $res = $this->isJwtActive($jwt);
        return $this->apiItem($res);
    }

    private function isJwtActive(string $jwt): array
    {
        $cfg = Yii::$app->params['jwt'] ?? [];
        $secret = $cfg['secret'] ?? null;
        $alg    = $cfg['alg']    ?? 'HS256';
        $leeway = (int)($cfg['leeway'] ?? 0);

        if (!$secret) {
            return ['active' => false, 'exp' => null];
        }

        if ($leeway > 0 && method_exists(JWT::class, 'setLeeway')) {
            JWT::setLeeway($leeway);
        }

        try {
            $decoded = JWT::decode($jwt, new Key($secret, $alg));
            $exp = isset($decoded->exp) ? (int)$decoded->exp : null;
            if ($exp !== null && $exp < time()) {
                return ['active' => false, 'exp' => $exp];
            }
            return ['active' => true, 'exp' => $exp];
        } catch (\Firebase\JWT\ExpiredException $e) {
            return ['active' => false, 'exp' => null];
        } catch (\Throwable $e) {
            return ['active' => false, 'exp' => null];
        }
    }
}