<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\ChangePasswordRequest;
use App\Http\Requests\Auth\LoginRequest;
use App\Services\AuthService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function __construct(protected AuthService $authService) {}

    public function login(LoginRequest $request): JsonResponse
    {
        $result = $this->authService->login(
            $request->input('username'),
            $request->input('password')
        );

        if ($result['code'] !== 0) {
            return response()->json($result, $result['code'] === 40001 ? 401 : 400);
        }

        return response()->json($result);
    }

    public function logout(Request $request): JsonResponse
    {
        $user = $request->user();

        // 清除 Session 认证（管理后台使用 auth:admin 中间件，基于 Session）
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return response()->json(
            $this->authService->logout($user)
        );
    }

    public function user(Request $request): JsonResponse
    {
        return response()->json(
            $this->authService->getUser($request->user())
        );
    }

    public function changePassword(ChangePasswordRequest $request): JsonResponse
    {
        $result = $this->authService->changePassword(
            $request->user(),
            $request->input('old_password'),
            $request->input('new_password')
        );

        if ($result['code'] !== 0) {
            return response()->json($result, 400);
        }

        return response()->json($result);
    }

    public function refresh(Request $request): JsonResponse
    {
        return response()->json(
            $this->authService->refresh($request->user())
        );
    }
}
