package com.yimeng.okr.controller;

import com.yimeng.okr.dto.*;
import com.yimeng.okr.annotation.OperationLogAnnotation;
import com.yimeng.okr.exception.BusinessException;
import com.yimeng.okr.service.AuthService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

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

    private final AuthService authService;

    @PostMapping("/login")
    @OperationLogAnnotation(action = "LOGIN", entityType = "auth", sensitive = true)
    public ApiResult<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        return ApiResult.success(authService.login(request));
    }

    @PostMapping("/register")
    @OperationLogAnnotation(action = "REGISTER_BLOCKED", entityType = "auth", sensitive = true)
    public ApiResult<LoginResponse> register(@Valid @RequestBody RegisterRequest request) {
        throw new BusinessException(403, "内部系统已关闭公开注册，请联系HR管理员创建账号");
    }

    @GetMapping("/me")
    public ApiResult<UserInfo> me(Authentication auth) {
        Long userId = (Long) auth.getPrincipal();
        return ApiResult.success(authService.getMe(userId));
    }

    @PutMapping("/password")
    @OperationLogAnnotation(action = "CHANGE_PASSWORD", entityType = "sys_user", sensitive = true)
    public ApiResult<Void> changePassword(Authentication auth, @RequestBody Map<String, String> body) {
        Long userId = (Long) auth.getPrincipal();
        authService.changePassword(userId, body.get("oldPassword"), body.get("newPassword"));
        return ApiResult.success();
    }

    @PostMapping("/refresh")
    @OperationLogAnnotation(action = "REFRESH_TOKEN", entityType = "auth", sensitive = true)
    public ApiResult<Map<String, String>> refreshToken(@RequestBody Map<String, String> body) {
        String refreshToken = body.get("refreshToken");
        return ApiResult.success(Map.of("accessToken", authService.refreshAccessToken(refreshToken)));
    }
}
