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

/**
 * 临时工登记接口。
 * <p>登录后若 {@code /getInfo} 返回 {@code registered=false}，跳转登记页提交实名与银行卡信息。</p>
 */
@RestController
@RequestMapping("/api/v1/mp/worker")
@Tag(name = "临时工", description = "首次登录登记，需 JWT 鉴权")
@SecurityRequirement(name = "Authorization")
public class WorkerController {

    private static final String USER_TYPE_WORKER = "worker";

    private final WorkerService workerService;

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

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

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