package com.yaoai.admin.auth;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.yaoai.common.result.Result;
import com.yaoai.domain.entity.AdminUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

@RestController
@RequestMapping("/admin-api/auth")
@RequiredArgsConstructor
public class AdminAuthController {

    private final AdminAuthService authService;

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginRequest req, HttpServletRequest request) {
        String ip = getClientIp(request);
        String token = authService.login(req.getUsername(), req.getPassword(), ip);
        return Result.ok(token);
    }

    @PostMapping("/logout")
    @SaCheckLogin(type = "admin")
    public Result<Void> logout() {
        authService.logout();
        return Result.ok();
    }

    @GetMapping("/me")
    @SaCheckLogin(type = "admin")
    public Result<AdminUser> me() {
        return Result.ok(authService.getCurrentAdmin());
    }

    @PostMapping("/change-password")
    @SaCheckLogin(type = "admin")
    public Result<Void> changePassword(@RequestBody ChangePasswordRequest req) {
        authService.changePassword(req.getOldPassword(), req.getNewPassword());
        return Result.ok();
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @Data
    static class LoginRequest {
        private String username;
        private String password;
    }

    @Data
    static class ChangePasswordRequest {
        private String oldPassword;
        private String newPassword;
    }
}
