package com.xindazhou.business.controller.app.tenant;

import com.xindazhou.framework.common.enums.CommonStatusEnum;
import com.xindazhou.framework.common.pojo.CommonResult;
import com.xindazhou.framework.common.util.object.BeanUtils;
import com.xindazhou.framework.tenant.core.aop.TenantIgnore;
import com.xindazhou.framework.tenant.config.TenantProperties;
import com.xindazhou.business.controller.app.tenant.vo.AppTenantRespVO;
import com.xindazhou.business.dal.dataobject.tenant.TenantDO;
import com.xindazhou.business.service.tenant.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.annotation.security.PermitAll;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.xindazhou.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 App - 租户")
@RestController
@RequestMapping("/system/tenant")
public class AppTenantController {

    @Resource
    private TenantService tenantService;

    @Autowired(required = false)
    private TenantProperties tenantProperties;

    @GetMapping("/get-by-website")
    @PermitAll
    @TenantIgnore
    @Operation(summary = "使用域名，获得租户信息", description = "根据用户的域名，获得租户信息")
    @Parameter(name = "website", description = "域名", required = true, example = "www.narutohuo.cn")
    public CommonResult<AppTenantRespVO> getTenantByWebsite(@RequestParam("website") String website) {
        // 如果多租户功能未启用，直接返回 null，避免查询数据库
        if (tenantProperties == null || !tenantProperties.getEnable()) {
            return success(null);
        }
        TenantDO tenant = tenantService.getTenantByWebsite(website);
        if (tenant == null || CommonStatusEnum.isDisable(tenant.getStatus())) {
            return success(null);
        }
        return success(BeanUtils.toBean(tenant, AppTenantRespVO.class));
    }

}
