package com.zioinfo.kintex.parking;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import com.zioinfo.kintex.parking.dto.ParkingDtos.MyPassesDto;
import com.zioinfo.kintex.parking.dto.ParkingDtos.ParkingLotStatusDto;
import com.zioinfo.kintex.parking.dto.ParkingDtos.ParkingPassDto;
import com.zioinfo.kintex.parking.dto.ParkingDtos.PurchasePassRequest;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
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;

import java.util.List;

/**
 * 관람객 주차 연계 API (F-C2).
 *
 * <p>권한 설계:
 * <ul>
 *   <li>주차 현황 {@code GET /api/public/parking/lots} — 공개(비로그인, {@code /api/public/**} permitAll).</li>
 *   <li>사전 주차권 구매/조회 {@code /api/parking/passes} — 인증 필요(로그인 관람객, 본인 소유분만).</li>
 * </ul>
 * 보안(§0-3): 응답에 차량번호 원문 미노출(마스킹만) · 스택트레이스 미노출(GlobalExceptionHandler).
 */
@RestController
public class ParkingController {

    private final ParkingService service;

    public ParkingController(ParkingService service) {
        this.service = service;
    }

    /** GET /api/public/parking/lots?eventId= — 주차장 실시간 현황(공개). 잔여·점유율·혼잡도·요금. */
    @GetMapping("/api/public/parking/lots")
    public ApiResponse<List<ParkingLotStatusDto>> lots(
            @RequestParam(required = false) String eventId) {
        return ApiResponse.ok(service.getLotStatus(eventId));
    }

    /** POST /api/parking/passes — 사전 주차권 구매(인증, mock 결제). */
    @PostMapping("/api/parking/passes")
    public ApiResponse<ParkingPassDto> purchase(@AuthenticationPrincipal KintexPrincipal principal,
                                                @Valid @RequestBody PurchasePassRequest req) {
        return ApiResponse.ok(service.purchasePass(requireUserId(principal), req));
    }

    /** GET /api/parking/passes/me — 내 주차권 목록(인증, 본인 소유분만). */
    @GetMapping("/api/parking/passes/me")
    public ApiResponse<MyPassesDto> myPasses(@AuthenticationPrincipal KintexPrincipal principal) {
        return ApiResponse.ok(new MyPassesDto(service.myPasses(requireUserId(principal))));
    }

    private static String requireUserId(KintexPrincipal principal) {
        if (principal == null || principal.userId() == null || principal.userId().isBlank()) {
            throw new ApiException(ErrorCode.UNAUTHORIZED, "로그인이 필요합니다.");
        }
        return principal.userId();
    }
}
