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.registration.WorkerRegistrationService;
import com.huimv.employment.service.registration.dto.WorkerRegistrationApplyRequest;
import com.huimv.employment.service.registration.dto.WorkerRegistrationApplyResponse;
import com.huimv.employment.service.registration.dto.WorkerRegistrationRejectRequest;
import com.huimv.employment.service.registration.dto.WorkerRegistrationReviewResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
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.PathVariable;
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;

/**
 * 临时工批次登记 / 用工邀请申请加入；企业审核。
 */
@RestController
@RequestMapping("/api/v1/mp/worker-registration")
@Tag(name = "用工邀请登记", description = "临时工申请加入；企业审核通过/驳回")
@SecurityRequirement(name = "Authorization")
public class WorkerRegistrationController {

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

    private final WorkerRegistrationService workerRegistrationService;

    public WorkerRegistrationController(WorkerRegistrationService workerRegistrationService) {
        this.workerRegistrationService = workerRegistrationService;
    }

    @PostMapping("/apply")
    @Operation(summary = "申请加入用工邀请",
            description = "临时工扫码进入用工邀约后调用。body.scene 为小程序码参数（订单编号）。"
                    + "需已完成档案登记；写入 fe_worker_registration（reg_status=under_review）。")
    public R<WorkerRegistrationApplyResponse> apply(@Validated @RequestBody WorkerRegistrationApplyRequest request) {
        LoginUser loginUser = requireWorker();
        return R.ok(workerRegistrationService.apply(loginUser.getUserId(), request));
    }

    @PostMapping("/{id}/approve")
    @Operation(summary = "企业审核通过用工登记",
            description = "企业主审核 under_review 登记：该人 reg_status→contract_signing；"
                    + "自动生成待签电子合同（fe_contract，幂等）；"
                    + "订单推进到 contract_signing。合同生成失败不影响审核结果，可调用重新生成接口。",
            parameters = {
                    @Parameter(name = "id", in = ParameterIn.PATH, required = true,
                            description = "fe_worker_registration.id（进度人员列表 registration_id）")
            })
    public R<WorkerRegistrationReviewResponse> approve(@PathVariable("id") Long id) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(workerRegistrationService.approve(loginUser.getUserId(), id));
    }

    @PostMapping("/{id}/reject")
    @Operation(summary = "企业驳回用工登记",
            description = "企业主驳回 under_review 登记：reg_status→rejected，必填 fail_reason；"
                    + "写 reviewed_at/reviewed_by，并释放批次/订单名额。",
            parameters = {
                    @Parameter(name = "id", in = ParameterIn.PATH, required = true,
                            description = "fe_worker_registration.id")
            })
    public R<WorkerRegistrationReviewResponse> reject(@PathVariable("id") Long id,
                                                      @RequestBody(required = false) WorkerRegistrationRejectRequest request) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(workerRegistrationService.reject(loginUser.getUserId(), id, request));
    }

    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;
    }
}
