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

/**
 * 临时工批次登记 / 用工邀请申请加入。
 */
@RestController
@RequestMapping("/api/v1/mp/worker-registration")
@Tag(name = "用工邀请登记", description = "扫码后申请加入用工批次，需临时工 JWT")
@SecurityRequirement(name = "Authorization")
public class WorkerRegistrationController {

    private static final String USER_TYPE_WORKER = "worker";

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

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