package com.huimv.employment.controller.mp;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import com.huimv.employment.common.web.R;
import com.huimv.employment.security.LoginUser;
import com.huimv.employment.security.LoginUserHolder;
import com.huimv.employment.service.worker.ThirdPartyWorkerService;
import com.huimv.employment.service.worker.WorkerService;
import com.huimv.employment.service.worker.dto.ThirdPartyWorkerGroupResponse;
import com.huimv.employment.service.worker.dto.ThirdPartyWorkerQueryItem;
import com.huimv.employment.service.worker.dto.WorkerRegisterRequest;
import com.huimv.employment.service.worker.dto.WorkerRegisterResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
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;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 临时工相关接口：档案登记、可用工人查询（第三方人力匹配 Mock）。
 */
@RestController
@RequestMapping("/api/v1/mp/worker")
@Tag(name = "临时工", description = "临时工登记与可用工人查询（Mock），需 JWT 鉴权")
@SecurityRequirement(name = "Authorization")
@Validated
public class WorkerController {

    private static final String USER_TYPE_WORKER = "worker";
    private static final String USER_TYPE_ENTERPRISE = "enterprise";

    private final WorkerService workerService;
    private final ThirdPartyWorkerService thirdPartyWorkerService;

    public WorkerController(WorkerService workerService,
                            ThirdPartyWorkerService thirdPartyWorkerService) {
        this.workerService = workerService;
        this.thirdPartyWorkerService = thirdPartyWorkerService;
    }

    @PostMapping("/register")
    @Operation(summary = "提交登记")
    public R<WorkerRegisterResponse> register(@Validated @RequestBody WorkerRegisterRequest request,
                                              HttpServletRequest httpRequest) {
        LoginUser loginUser = requireWorker();
        return R.ok(workerService.register(
                loginUser.getUserId(),
                request,
                httpRequest.getRemoteAddr(),
                httpRequest.getHeader("User-Agent")));
    }

    @PostMapping("/third-party/available")
    @Operation(summary = "第三方可用工人查询（Mock）",
            description = "请求体为条件数组，示例：[{\"jobType\":\"搬运工\",\"workLocation\":\"上海\"}]。"
                    + "jobType 与 Mock 中 confirmed_work_type 精确匹配；workLocation 可选（包含匹配）。"
                    + "按工种分组返回 groups[].workers，含 mobile / id_card_no 明文（便于添加第三方工人）。"
                    + "MVP Mock：classpath mock/available-workers.json。需企业 JWT。")
    public R<ThirdPartyWorkerGroupResponse> listAvailable(
            @RequestBody @NotEmpty(message = "查询条件不能为空")
            List<@Valid ThirdPartyWorkerQueryItem> queries) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(thirdPartyWorkerService.listAvailable(loginUser.getUserId(), queries));
    }

    private static LoginUser requireWorker() {
        LoginUser loginUser = LoginUserHolder.require();
        if (!USER_TYPE_WORKER.equals(loginUser.getUserType())) {
            throw new BizException(ErrorCode.WORKER_ONLY);
        }
        return loginUser;
    }

    private static LoginUser requireEnterprise() {
        LoginUser loginUser = LoginUserHolder.require();
        if (!USER_TYPE_ENTERPRISE.equals(loginUser.getUserType())) {
            throw new BizException(ErrorCode.ENTERPRISE_ONLY);
        }
        return loginUser;
    }
}
