package com.example.demo.controller.auth;

import com.example.demo.common.ApiResponse;
import com.example.demo.dto.auth.LoginRequest;
import com.example.demo.security.LearningJwtUtil;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class LearningAuthController {

    private final LearningJwtUtil jwtUtil;

    public LearningAuthController(LearningJwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody LoginRequest req) {
        // 学习演示：仅做最小账号检查
        if (!(("admin".equals(req.username()) && "admin123".equals(req.password()))
                || ("user".equals(req.username()) && "user123".equals(req.password())))) {
            return new ApiResponse<>(401, "用户名或密码错误", null, java.time.Instant.now());
        }
        String token = jwtUtil.generateToken(req.username());
        return ApiResponse.ok(Map.of(
                "token", token,
                "type", "Bearer",
                "username", req.username(),
                "tip", "在请求头中加入 Authorization: Bearer <token> 访问 /api/secure/**"
        ));
    }

    @GetMapping("/mode")
    public ApiResponse<Map<String, Object>> mode() {
        return ApiResponse.ok(Map.of(
                "mode", "learning-jwt",
                "protectedPath", "/api/secure/**",
                "defaultAccounts", "admin/admin123, user/user123"
        ));
    }
}
