package com.vibevault.controller;

import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import com.vibevault.model.User;
import com.vibevault.repository.UserRepository;
import com.vibevault.security.JwtService;

/**
 * 认证控制器
 * 
 * 需要实现以下端点：
 * - POST /api/auth/register - 用户注册
 *   - 检查用户名是否已存在（已存在返回 409 Conflict）
 *   - 密码需要加密存储
 *   - 成功返回 201
 * 
 * - POST /api/auth/login - 用户登录
 *   - 验证用户名和密码
 *   - 验证失败返回 401 Unauthorized
 *   - 验证成功返回 JWT token
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;

    public AuthController(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtService jwtService) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.jwtService = jwtService;
    }

    // POST /api/auth/register - 用户注册
    @PostMapping("/register")
    @ResponseStatus(HttpStatus.CREATED)
    public RegisterResponse register(@RequestBody RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.username())) {
            throw new ResponseStatusException(HttpStatus.CONFLICT, "Username already exists");
        }

        // 创建新用户，加密密码
        User user = new User(request.username(), passwordEncoder.encode(request.password()));

        // 保存用户到数据库
        userRepository.save(user);

        return new RegisterResponse("User registered successfully", user.getUsername());
    }

    // POST /api/auth/login - 用户登录
    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginRequest request) {
        // 检查用户名是否存在
        User user = userRepository.findByUsername(request.username())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid username or password"));

        // 验证密码
        if (!passwordEncoder.matches(request.password(), user.getPassword())) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid username or password");
        }

        // 生成JWT token
        String token = jwtService.generateToken(user.getUsername());

        return new LoginResponse(token, user.getUsername());
    }
}

/**
 * 注册请求 DTO
 */
record RegisterRequest(String username, String password) {}

/**
 * 注册响应 DTO
 */
record RegisterResponse(String message, String username) {}

/**
 * 登录请求 DTO
 */
record LoginRequest(String username, String password) {}

/**
 * 登录响应 DTO
 */
record LoginResponse(String token, String username) {}
