package com.competition.modules.sys.controller;

import com.competition.common.result.Result;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.sys.dto.LoginDto;
import com.competition.modules.sys.service.AuthService;
import com.competition.security.annotation.Public;
import io.swagger.v3.oas.annotations.Operation;
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.*;

import java.util.Map;

@Tag(name = "认证管理")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @Public
    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDto dto, HttpServletRequest request) {
        // 优先从请求头获取租户 ID，其次从 body 的 tenantCode 查找
        String tenantIdHeader = request.getHeader("X-Tenant-Id");
        Long tenantId = tenantIdHeader != null && !tenantIdHeader.isBlank() ? Long.parseLong(tenantIdHeader) : null;

        return Result.success(authService.login(dto.getUsername(), dto.getPassword(), tenantId, dto.getTenantCode()));
    }

    @GetMapping("/user-info")
    @Operation(summary = "获取当前用户信息")
    public Result<Map<String, Object>> getUserInfo() {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(authService.getUserInfo(userId));
    }

    @PostMapping("/logout")
    @Operation(summary = "登出")
    public Result<Map<String, String>> logout() {
        return Result.success(Map.of("message", "登出成功"));
    }
}
