package com.zioinfo.kintex.logistics;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.logistics.dto.DockBoardDto;
import com.zioinfo.kintex.logistics.dto.DockForecastDto;
import com.zioinfo.kintex.logistics.dto.DockGridReservationDto;
import com.zioinfo.kintex.logistics.dto.DockReservationRequest;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * M8 반입/반출 도크 슬롯 예약 API (SCR-25). 행사 RBAC 가드. 슬롯 중복은 409 CONFLICT.
 */
@RestController
@RequestMapping("/api/events/{eventId}")
public class LogisticsController {

    private final LogisticsService service;
    private final EventAccessGuard guard;

    public LogisticsController(LogisticsService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    /** GET /docks?direction=in|out&date=YYYY-MM-DD — 도크 현황판(그리드). */
    @GetMapping("/docks")
    public ApiResponse<DockBoardDto> docks(@AuthenticationPrincipal KintexPrincipal principal,
                                           @PathVariable String eventId,
                                           @RequestParam(required = false, defaultValue = "in") String direction,
                                           @RequestParam(required = false) String date) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getBoard(eventId, direction, date));
    }

    /** POST /dock-reservations — 슬롯 예약(중복 시 409). */
    @PostMapping("/dock-reservations")
    public ApiResponse<DockGridReservationDto> reserve(@AuthenticationPrincipal KintexPrincipal principal,
                                                       @PathVariable String eventId,
                                                       @RequestBody DockReservationRequest request) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.createReservation(eventId, request));
    }

    /** GET /dock-forecast?date=YYYY-MM-DD — 철거일 대기열 예측(단순 시간대 집계, 부재 시 폴백). */
    @GetMapping("/dock-forecast")
    public ApiResponse<DockForecastDto> forecast(@AuthenticationPrincipal KintexPrincipal principal,
                                                 @PathVariable String eventId,
                                                 @RequestParam(required = false) String date) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getForecast(eventId, date));
    }
}
