package com.zioinfo.esn.uiws.schedule.controller;

import com.zioinfo.esn.common.ApiResponse;
import com.zioinfo.esn.uiws.schedule.dto.ScheduleDtos.*;
import com.zioinfo.esn.uiws.schedule.service.ScheduleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

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

/**
 * UIWS 이식 — 일정(모듈 02). 인증 필수(/api/schedules). 원본 엔드포인트 보존.
 */
@RestController
@RequestMapping("/api/schedules")
@RequiredArgsConstructor
public class ScheduleController {

    private final ScheduleService scheduleService;

    @GetMapping
    public ApiResponse<List<ScheduleDto>> calendar(
            @RequestParam(defaultValue = "PERSONAL") String type,
            @RequestParam(defaultValue = "month") String view,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate baseDate,
            @RequestParam(required = false) String deptId) {
        return ApiResponse.ok(scheduleService.calendar(type, view, baseDate, deptId));
    }

    @GetMapping("/all")
    public ApiResponse<SchedulePage> all(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate,
            @RequestParam(required = false) String type,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ApiResponse.ok(scheduleService.all(fromDate, toDate, type, page, size));
    }

    @GetMapping("/search")
    public ApiResponse<List<ScheduleDto>> search(@RequestParam(required = false) String keyword) {
        return ApiResponse.ok(scheduleService.search(keyword));
    }

    @PostMapping
    public ApiResponse<ScheduleDto> create(@Valid @RequestBody ScheduleSaveDto dto) {
        return ApiResponse.ok(scheduleService.create(dto));
    }

    @GetMapping("/{id}")
    public ApiResponse<ScheduleDetailDto> detail(@PathVariable("id") Long id) {
        return ApiResponse.ok(scheduleService.detail(id));
    }

    @PutMapping("/{id}")
    public ApiResponse<ScheduleDetailDto> update(@PathVariable("id") Long id, @Valid @RequestBody ScheduleSaveDto dto) {
        return ApiResponse.ok(scheduleService.update(id, dto));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        scheduleService.delete(id);
        return ApiResponse.ok(null);
    }
}
