package com.zioinfo.kintex.module.m3;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.EventRole;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.module.m3.dto.DesignPlanDto;
import com.zioinfo.kintex.module.m3.dto.DesignSaveRequest;
import com.zioinfo.kintex.module.m3.dto.DesignSpec;
import com.zioinfo.kintex.rules.ComplianceReport;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

/**
 * M3 부스 설계 스튜디오 API (SCR-06/09).
 * 참가업체(조립 옵션·컨펌)·장치업체(독립 편집)가 설계/사전검증한다. 행사 RBAC 가드로 접근 제어.
 */
@RestController
@RequestMapping("/api/events/{eventId}/booths/{boothId}/design")
public class DesignController {

    private final DesignService service;
    private final EventAccessGuard guard;

    public DesignController(DesignService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    /** GET — 설계안 조회(행사 멤버/홀매니저). */
    @GetMapping
    public ApiResponse<DesignPlanDto> get(@AuthenticationPrincipal KintexPrincipal principal,
                                          @PathVariable String eventId,
                                          @PathVariable String boothId,
                                          @RequestParam(required = false) Integer version) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getDesign(boothId, version));
    }

    /** PUT — 설계 저장(참가업체/장치업체). */
    @PutMapping
    public ApiResponse<DesignPlanDto> save(@AuthenticationPrincipal KintexPrincipal principal,
                                           @PathVariable String eventId,
                                           @PathVariable String boothId,
                                           @Valid @RequestBody DesignSaveRequest request) {
        guard.requireRole(principal, eventId, EventRole.EXHIBITOR, EventRole.CONTRACTOR);
        return ApiResponse.ok(service.saveDesign(boothId, request));
    }

    /** POST /precheck — 규정 사전검증(제출 전 플래깅). 스펙만으로 즉시 평가(완성 구현). */
    @PostMapping("/precheck")
    public ApiResponse<ComplianceReport> precheck(@AuthenticationPrincipal KintexPrincipal principal,
                                                  @PathVariable String eventId,
                                                  @PathVariable String boothId,
                                                  @Valid @RequestBody DesignSpec spec) {
        guard.requireRole(principal, eventId, EventRole.EXHIBITOR, EventRole.CONTRACTOR,
                EventRole.HALL_MANAGER);
        return ApiResponse.ok(service.precheck(spec));
    }
}
