package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.DesignService;
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/design")
@RequiredArgsConstructor
@Slf4j
public class DesignController {

    private final DesignService designService;

    // ============================================
    // 설계의뢰 (Design Request)
    // ============================================

    @GetMapping("/requests")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDesignRequestList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(designService.getDesignRequestList(params)));
    }

    @GetMapping("/requests/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDesignRequestDetail(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id) {
        Map<String, Object> result = designService.getDesignRequestDetail(id, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("의뢰를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping("/requests")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createDesignRequest(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createDesignRequest(body, companyCode, userId)));
    }

    @PutMapping("/requests/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateDesignRequest(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateDesignRequest(id, body, companyCode, userId);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("의뢰를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/requests/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteDesignRequest(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id) {
        boolean deleted = designService.deleteDesignRequest(id, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("의뢰를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    @PostMapping("/requests/{id}/history")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addRequestHistory(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.addRequestHistory(id, body, companyCode, userId)));
    }

    // ============================================
    // 설계 프로젝트
    // ============================================

    @GetMapping("/projects")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getProjectList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(designService.getProjectList(params)));
    }

    @GetMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getProjectDetail(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id) {
        Map<String, Object> result = designService.getProjectDetail(id, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("프로젝트를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping("/projects")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createProject(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createProject(body, companyCode, userId)));
    }

    @PutMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateProject(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateProject(id, body, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("프로젝트를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteProject(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id) {
        boolean deleted = designService.deleteProject(id, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("프로젝트를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ============================================
    // 프로젝트 태스크
    // ============================================

    @GetMapping("/projects/{projectId}/tasks")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTasksByProject(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String projectId) {
        return ResponseEntity.ok(ApiResponse.success(designService.getTasksByProject(projectId, companyCode)));
    }

    @PostMapping("/projects/{projectId}/tasks")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTask(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String projectId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createTask(projectId, body, companyCode, userId)));
    }

    @PutMapping("/tasks/{taskId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateTask(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String taskId,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateTask(taskId, body, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("태스크를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/tasks/{taskId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteTask(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String taskId) {
        boolean deleted = designService.deleteTask(taskId, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("태스크를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ============================================
    // 작업일지
    // ============================================

    @GetMapping("/tasks/{taskId}/work-logs")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getWorkLogsByTask(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String taskId) {
        return ResponseEntity.ok(ApiResponse.success(designService.getWorkLogsByTask(taskId, companyCode)));
    }

    @PostMapping("/tasks/{taskId}/work-logs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createWorkLog(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String taskId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createWorkLog(taskId, body, companyCode, userId)));
    }

    @DeleteMapping("/work-logs/{workLogId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteWorkLog(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String workLogId) {
        boolean deleted = designService.deleteWorkLog(workLogId, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("작업일지를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ============================================
    // 태스크 하위항목
    // ============================================

    @PostMapping("/tasks/{taskId}/sub-items")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createSubItem(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String taskId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createSubItem(taskId, body, companyCode, userId)));
    }

    @PutMapping("/sub-items/{subItemId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateSubItem(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String subItemId,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateSubItem(subItemId, body, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("하위항목을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/sub-items/{subItemId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSubItem(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String subItemId) {
        boolean deleted = designService.deleteSubItem(subItemId, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("하위항목을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ============================================
    // 태스크 이슈
    // ============================================

    @PostMapping("/tasks/{taskId}/issues")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createIssue(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String taskId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createIssue(taskId, body, companyCode, userId)));
    }

    @PutMapping("/issues/{issueId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateIssue(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String issueId,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateIssue(issueId, body, companyCode);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("이슈를 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    // ============================================
    // ECN (설변통보)
    // ============================================

    @GetMapping("/ecn")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getEcnList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(designService.getEcnList(params)));
    }

    @PostMapping("/ecn")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createEcn(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createEcn(body, companyCode, userId)));
    }

    @PutMapping("/ecn/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateEcn(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = designService.updateEcn(id, body, companyCode, userId);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("ECN을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/ecn/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteEcn(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id) {
        boolean deleted = designService.deleteEcn(id, companyCode);
        if (!deleted) return ResponseEntity.status(404).body(ApiResponse.error("ECN을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ============================================
    // 나의 업무
    // ============================================

    @GetMapping("/my-work")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMyWork(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_name", required = false) String userName,
            @RequestParam Map<String, Object> params) {
        return ResponseEntity.ok(ApiResponse.success(designService.getMyWork(params, companyCode, userName)));
    }

    // ============================================
    // 구매요청 / 협업요청
    // ============================================

    @PostMapping("/work-logs/{workLogId}/purchase-reqs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createPurchaseReq(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String workLogId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createPurchaseReq(workLogId, body, companyCode, userId)));
    }

    @PostMapping("/work-logs/{workLogId}/coop-reqs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createCoopReq(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String workLogId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.createCoopReq(workLogId, body, companyCode, userId)));
    }

    @PostMapping("/coop-reqs/{coopReqId}/responses")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addCoopResponse(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String coopReqId,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(designService.addCoopResponse(coopReqId, body, companyCode, userId)));
    }
}
