package com.snack.server.module.admin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.server.common.Result;
import com.snack.server.module.admin.dto.req.AdminLoginReq;
import com.snack.server.module.admin.dto.req.AdminPageReq;
import com.snack.server.module.admin.dto.req.AdminProfileReq;
import com.snack.server.module.admin.dto.req.AdminSaveReq;
import com.snack.server.module.admin.dto.req.ChangePasswordReq;
import com.snack.server.module.admin.service.AdminService;
import com.snack.server.module.admin.vo.AdminVO;
import com.snack.server.module.admin.vo.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员相关接口
 */
@Tag(name = "01. 管理员管理")
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminService adminService;

    // ==================== 鉴权相关（白名单） ====================

    @Operation(summary = "管理员登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody AdminLoginReq req, HttpServletRequest request) {
        String ip = getClientIp(request);
        return Result.ok(adminService.login(req, ip));
    }

    @Operation(summary = "管理员登出")
    @SaCheckLogin
    @PostMapping("/logout")
    public Result<Void> logout() {
        adminService.logout();
        return Result.ok();
    }

    @Operation(summary = "获取当前登录管理员信息")
    @SaCheckLogin
    @GetMapping("/info")
    public Result<AdminVO> getCurrentAdmin() {
        return Result.ok(adminService.getCurrentAdmin());
    }

    @Operation(summary = "修改自己的密码")
    @SaCheckLogin
    @PutMapping("/password")
    public Result<Void> changePassword(@Valid @RequestBody ChangePasswordReq req) {
        adminService.changePassword(req);
        return Result.ok();
    }

    @Operation(summary = "更新自己的个人资料（昵称/头像/邮箱/手机号）")
    @SaCheckLogin
    @PutMapping("/profile")
    public Result<Void> updateProfile(@Valid @RequestBody AdminProfileReq req) {
        adminService.updateProfile(req);
        return Result.ok();
    }

    // ==================== 管理员 CRUD ====================

    @Operation(summary = "分页查询管理员列表")
    @SaCheckLogin
    @GetMapping("/page")
    public Result<Page<AdminVO>> page(AdminPageReq req) {
        return Result.ok(adminService.pageAdmins(req));
    }

    @Operation(summary = "获取管理员详情")
    @SaCheckLogin
    @GetMapping("/{id}")
    public Result<AdminVO> detail(@Parameter(description = "管理员 ID") @PathVariable Long id) {
        return Result.ok(adminService.getAdminById(id));
    }

    @Operation(summary = "创建管理员")
    @SaCheckRole("super_admin")
    @PostMapping
    public Result<Long> create(@Valid @RequestBody AdminSaveReq req) {
        return Result.ok(adminService.createAdmin(req));
    }

    @Operation(summary = "更新管理员")
    @SaCheckRole("super_admin")
    @PutMapping
    public Result<Void> update(@Valid @RequestBody AdminSaveReq req) {
        adminService.updateAdmin(req);
        return Result.ok();
    }

    @Operation(summary = "删除管理员")
    @SaCheckRole("super_admin")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@Parameter(description = "管理员 ID") @PathVariable Long id) {
        adminService.deleteAdmin(id);
        return Result.ok();
    }

    @Operation(summary = "重置管理员密码")
    @SaCheckRole("super_admin")
    @PutMapping("/{id}/password/reset")
    public Result<Void> resetPassword(
            @Parameter(description = "管理员 ID") @PathVariable Long id,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        adminService.resetPassword(id, newPassword);
        return Result.ok();
    }

    @Operation(summary = "启用/禁用管理员")
    @SaCheckRole("super_admin")
    @PutMapping("/{id}/status/{status}")
    public Result<Void> updateStatus(
            @Parameter(description = "管理员 ID") @PathVariable Long id,
            @Parameter(description = "状态：0-禁用 1-启用") @PathVariable Integer status) {
        adminService.updateStatus(id, status);
        return Result.ok();
    }

    // ==================== 工具方法 ====================

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多级代理取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
