package com.carmaintenance.controller;

import com.carmaintenance.dto.LoginRequest;
import com.carmaintenance.dto.LoginResponse;
import com.carmaintenance.dto.Result;
import com.carmaintenance.entity.User;
import com.carmaintenance.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {
        if (request.getUsername() == null || request.getPassword() == null) {
            return Result.error("用户名和密码不能为空");
        }

        User user = userRepository.findByUsernameAndPassword(
                request.getUsername(),
                request.getPassword()
        ).orElse(null);

        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        if (user.getStatus() != 1) {
            return Result.error("账号已被禁用");
        }

        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo(
                user.getUserId(),
                user.getUsername(),
                user.getRealName(),
                user.getPhone(),
                user.getEmail(),
                user.getRole().name()
        );

        String token = "TOKEN_" + user.getUserId() + "_" + System.currentTimeMillis();

        LoginResponse response = new LoginResponse(token, userInfo);
        return Result.success("登录成功", response);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            return Result.error("用户名已存在");
        }

        if (userRepository.existsByPhone(user.getPhone())) {
            return Result.error("手机号已被注册");
        }

        user.setRole(User.UserRole.customer);
        user.setStatus(1);
        User savedUser = userRepository.save(user);
        savedUser.setPassword(null);

        return Result.success("注册成功", savedUser);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        return Result.<Void>success("退出成功", null);
    }
}
