package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ScheduleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/schedule")
@RequiredArgsConstructor
@Slf4j
public class ScheduleController {
    private final ScheduleService scheduleService;

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getScheduleList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        List<Map<String, Object>> list = scheduleService.getScheduleList(params);
        Map<String, Object> resp = new LinkedHashMap<>();
        resp.put("success", true);
        resp.put("data", list);
        resp.put("total", list.size());
        return ResponseEntity.ok(resp);
    }

    @GetMapping("/{scheduleId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getScheduleInfo(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long scheduleId) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("schedule_id", scheduleId);
        return ResponseEntity.ok(ApiResponse.success(scheduleService.getScheduleInfo(params)));
    }

    /**
     * 스케줄 미리보기 (DB 저장 없음)
     * POST /api/schedule/preview
     */
    @PostMapping("/preview")
    public ResponseEntity<ApiResponse<Map<String, Object>>> previewSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        try {
            Map<String, Object> preview = scheduleService.previewSchedule(body);
            return ResponseEntity.ok(ApiResponse.success(preview));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 스케줄 적용 (DB 저장)
     * POST /api/schedule/apply
     */
    @PostMapping("/apply")
    public ResponseEntity<ApiResponse<Map<String, Object>>> applySchedules(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        try {
            Map<String, Object> applied = scheduleService.applySchedules(body);
            String message = applied.get("created") + "건 생성, " + applied.get("deleted") + "건 삭제, " + applied.get("updated") + "건 수정되었습니다.";
            return ResponseEntity.ok(ApiResponse.success(applied, message));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Integer>> insertSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(scheduleService.insertSchedule(body)));
    }

    @PutMapping("/{scheduleId}")
    public ResponseEntity<ApiResponse<Integer>> updateSchedule(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long scheduleId,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("schedule_id", scheduleId);
        return ResponseEntity.ok(ApiResponse.success(scheduleService.updateSchedule(body)));
    }

    @DeleteMapping("/{scheduleId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable Long scheduleId) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("user_id", userId);
        params.put("schedule_id", scheduleId);
        Map<String, Object> result = scheduleService.deleteSchedule(params);
        if (Boolean.FALSE.equals(result.get("success"))) {
            return ResponseEntity.status(404).body(ApiResponse.error((String) result.get("message")));
        }
        return ResponseEntity.ok(ApiResponse.success(result, "스케줄이 삭제되었습니다."));
    }
}
