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.contract.ContractService;
import com.huimv.employment.service.contract.dto.ContractItemResponse;
import com.huimv.employment.service.contract.dto.ContractSummaryResponse;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 电子合同：临时工列表/签署确认；企业端重新生成待签合同。
 */
@RestController
@RequestMapping("/api/v1/mp/contracts")
@Tag(name = "电子合同", description = "临时工查看与签署；企业重生成待签合同")
@SecurityRequirement(name = "Authorization")
public class ContractController {

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

    private final ContractService contractService;

    public ContractController(ContractService contractService) {
        this.contractService = contractService;
    }

    @GetMapping
    @Operation(summary = "我的电子合同列表",
            description = "临时工 JWT；按 worker_id 查询本人合同。可选 sign_status=pending|signing|signed 过滤。")
    public R<List<ContractItemResponse>> listMine(
            @RequestParam(value = "sign_status", required = false) String signStatus) {
        LoginUser loginUser = requireWorker();
        return R.ok(contractService.listMyContracts(loginUser.getUserId(), signStatus));
    }

    @GetMapping("/{id}")
    @Operation(summary = "合同详情",
            description = "临时工查看本人合同详情",
            parameters = {
                    @Parameter(name = "id", in = ParameterIn.PATH, required = true, description = "fe_contract.id")
            })
    public R<ContractItemResponse> detail(@PathVariable("id") Long id) {
        LoginUser loginUser = requireWorker();
        return R.ok(contractService.getMyContract(loginUser.getUserId(), id));
    }

    @PostMapping("/{id}/confirm-sign")
    @Operation(summary = "确认签署完成",
            description = "临时工确认签署（Mock 闭环）。sign_status→signed，登记 contract_signing→completed。"
                    + "订单不自动开工，须企业调用 POST /orders/{orderId}/start-work。已签署幂等返回。",
            parameters = {
                    @Parameter(name = "id", in = ParameterIn.PATH, required = true, description = "fe_contract.id")
            })
    public R<ContractItemResponse> confirmSign(@PathVariable("id") Long id) {
        LoginUser loginUser = requireWorker();
        return R.ok(contractService.confirmSign(loginUser.getUserId(), id));
    }

    @PostMapping("/by-registration/{registrationId}/regenerate")
    @Operation(summary = "重新生成待签合同",
            description = "电子签失败或签署链接缺失时调用。同一 registration 幂等；已签署不可重生成。",
            parameters = {
                    @Parameter(name = "registrationId", in = ParameterIn.PATH, required = true,
                            description = "fe_worker_registration.id")
            })
    public R<ContractSummaryResponse> regenerate(@PathVariable("registrationId") Long registrationId) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(contractService.regeneratePendingContract(loginUser.getUserId(), registrationId));
    }

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

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