package com.competition.modules.sys.controller;

import com.competition.common.result.PageResult;
import com.competition.common.result.Result;
import com.competition.common.exception.BusinessException;
import com.competition.common.enums.ErrorCode;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.sys.dto.CreateTenantDto;
import com.competition.modules.sys.dto.UpdateTenantDto;
import com.competition.modules.sys.entity.SysMenu;
import com.competition.modules.sys.entity.SysTenant;
import com.competition.modules.sys.service.ISysMenuService;
import com.competition.modules.sys.service.ISysTenantService;
import com.competition.security.annotation.RequirePermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.List;
import java.util.Objects;

@Tag(name = "租户管理")
@RestController
@RequestMapping("/tenants")
@RequiredArgsConstructor
public class SysTenantController {

    private final ISysTenantService tenantService;
    private final ISysMenuService menuService;

    @PostMapping
    @RequirePermission("tenant:create")
    @Operation(summary = "创建租户（自动创建管理员账号、角色、权限）")
    public Result<Map<String, Object>> create(@Valid @RequestBody CreateTenantDto dto) {
        Long currentTenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(tenantService.createTenant(dto, currentTenantId));
    }

    @GetMapping
    @RequirePermission("tenant:read")
    @Operation(summary = "查询租户列表")
    public Result<PageResult<Map<String, Object>>> findAll(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tenantType) {
        return Result.success(tenantService.findAll(page, pageSize, keyword, tenantType));
    }

    @PatchMapping("/{id}/status")
    @RequirePermission("tenant:update")
    @Operation(summary = "切换租户状态")
    public Result<Void> toggleStatus(@PathVariable Long id) {
        Long currentTenantId = SecurityUtil.getCurrentTenantId();
        tenantService.toggleStatus(id, currentTenantId);
        return Result.success();
    }

    @GetMapping("/my-tenant")
    @Operation(summary = "获取当前租户信息")
    public Result<SysTenant> getMyTenant() {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(tenantService.getMyTenant(tenantId));
    }

    @PatchMapping("/my-tenant")
    @Operation(summary = "更新当前租户信息")
    public Result<Void> updateMyTenant(@RequestBody Map<String, String> body) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        tenantService.updateMyTenant(tenantId, body.get("name"), body.get("description"));
        return Result.success();
    }

    @GetMapping("/{id}")
    @RequirePermission("tenant:read")
    @Operation(summary = "查询租户详情")
    public Result<Map<String, Object>> findOne(@PathVariable Long id) {
        return Result.success(tenantService.findDetail(id));
    }

    @PatchMapping("/{id}")
    @RequirePermission("tenant:update")
    @Operation(summary = "更新租户")
    public Result<SysTenant> update(@PathVariable Long id, @RequestBody UpdateTenantDto dto) {
        Long currentTenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(tenantService.updateTenant(id, dto, currentTenantId));
    }

    @DeleteMapping("/{id}")
    @RequirePermission("tenant:delete")
    @Operation(summary = "删除租户")
    public Result<Void> remove(@PathVariable Long id) {
        Long currentTenantId = SecurityUtil.getCurrentTenantId();
        tenantService.removeTenant(id, currentTenantId);
        return Result.success();
    }

    @GetMapping("/{id}/menus")
    @RequirePermission("tenant:read")
    @Operation(summary = "获取租户菜单树")
    public Result<List<SysMenu>> getTenantMenus(@PathVariable Long id) {
        Long currentTenantId = SecurityUtil.getCurrentTenantId();
        boolean isSuperAdmin = SecurityUtil.isSuperAdmin();

        // 非超管只能查询自身租户
        if (!isSuperAdmin && !Objects.equals(id, currentTenantId)) {
            throw BusinessException.of(ErrorCode.FORBIDDEN, "只能查询当前租户菜单");
        }

        // 校验租户是否存在
        if (tenantService.getById(id) == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "租户不存在");
        }

        return Result.success(menuService.getTenantMenus(id));
    }
}
