<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\RefreshRequest;
use App\Services\AuthService;
use Illuminate\Http\JsonResponse;

class RefreshController extends Controller
{
    /**
     * 리프레시 토큰으로 새로운 액세스 토큰을 발급합니다.
     */
    public function refresh(RefreshRequest $request): JsonResponse
    {
        $refreshToken = $request->validated()['refresh_token'];

        // 리프레시 토큰으로 새로운 토큰 발급
        $tokens = AuthService::refreshTokens($refreshToken);

        if (! $tokens) {
            return response()->json([
                'error' => __('error.refresh_token_invalid_or_expired'),
                'error_code' => 'TOKEN_EXPIRED',
            ], 401);
        }

        return response()->json([
            'message' => __('message.token_refreshed'),
            'access_token' => $tokens['access_token'],
            'refresh_token' => $tokens['refresh_token'],
            'token_type' => $tokens['token_type'],
            'expires_in' => $tokens['expires_in'],
            'expires_at' => $tokens['expires_at'],
        ]);
    }
}
