package com.toyshop.controller;

import com.toyshop.dto.*;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import com.toyshop.repository.UserRepository;
import com.toyshop.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
  private final AuthService authService;
  private final UserRepository userRepository;
  private final PasswordEncoder passwordEncoder;

  public AuthController(AuthService authService, UserRepository userRepository, PasswordEncoder passwordEncoder) {
    this.authService = authService;
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
  }

  @PostMapping("/register")
  public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
    String token = authService.register(request);
    return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
  }

  @PostMapping("/login")
  public ApiResponse<AuthResponse> login(@Valid @RequestBody AuthRequest request) {
    String token = authService.login(request);
    return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
  }

  @PostMapping("/admin/login")
  public ApiResponse<AuthResponse> adminLogin(@Valid @RequestBody AuthRequest request) {
    User user = userRepository.findByUsername(request.getUsername()).orElseThrow();
    if (user.getRole() != UserRole.ADMIN) {
      return ApiResponse.fail("非管理员账号");
    }
    if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
      return ApiResponse.fail("用户名或密码错误");
    }
    String token = authService.login(request);
    return ApiResponse.ok(new AuthResponse(token, "ADMIN", request.getUsername()));
  }
}
