package com.zioinfo.mall.schedule;

import com.zioinfo.mall.admin.AuditService;
import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 스케줄 API — /api/mall/schedule.
 * 가용 슬롯 조회는 공개(체크아웃 캘린더). 슬롯/공휴일 정의는 MANAGER+.
 */
@RestController
@RequestMapping("/api/mall/schedule")
@RequiredArgsConstructor
public class ScheduleController {

    private final ScheduleService service;
    private final AuditService auditService;

    /** 가용 슬롯 + 당일마감 + 서지 — 공개. */
    @GetMapping("/availability")
    public ApiResponse<Map<String, Object>> availability(
            @RequestParam Long storeId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return ApiResponse.ok(service.availability(storeId, date));
    }

    /** 공휴일 블록아웃/서지 목록 — 공개(캘린더 표시용). */
    @GetMapping("/holidays")
    public ApiResponse<List<MallHoliday>> holidays() {
        return ApiResponse.ok(service.holidays());
    }

    @PostMapping("/slot")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallScheduleSlot> createSlot(@RequestBody MallScheduleSlot s) {
        return ApiResponse.ok(service.createSlot(s));
    }

    /** 피크시즌 차단/서지 설정 (관리자앱 ⑥). */
    @PostMapping("/holiday")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallHoliday> upsertHoliday(@RequestBody MallHoliday h) {
        MallHoliday saved = service.upsertHoliday(h);
        auditService.log("HOLIDAY_SET", String.valueOf(h.getHolidayDate()),
                "blocked=" + h.getBlocked() + ",surge=" + h.getSurgeMultiplier());
        return ApiResponse.ok(saved);
    }
}
