package com.erp.controller;

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

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/api/admin/template-standards")
@RequiredArgsConstructor
public class TemplateStandardController {

    private final TemplateStandardService templateStandardService;

    /**
     * GET /api/admin/template-standards
     * 템플릿 목록 조회 (페이지네이션)
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getTemplateStandardList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {

        params.putIfAbsent("company_code", companyCode);

        Map<String, Object> result = templateStandardService.getTemplateStandardList(params);

        int total = ((Number) result.get("total")).intValue();
        int page  = ((Number) result.get("page")).intValue();
        int limit = ((Number) result.get("limit")).intValue();

        Map<String, Object> pagination = new LinkedHashMap<>();
        pagination.put("total",      total);
        pagination.put("page",       page);
        pagination.put("limit",      limit);
        pagination.put("total_pages", (int) Math.ceil((double) total / limit));

        Map<String, Object> response = new LinkedHashMap<>();
        response.put("success",    true);
        response.put("data",       result.get("templates"));
        response.put("pagination", pagination);

        return ResponseEntity.ok(response);
    }

    /**
     * GET /api/admin/template-standards/categories
     * 템플릿 카테고리 목록 조회
     */
    @GetMapping("/categories")
    public ResponseEntity<ApiResponse<List<String>>> getTemplateStandardCategoryList(
            @RequestAttribute("company_code") String companyCode) {

        List<String> categories = templateStandardService.getTemplateStandardCategoryList(companyCode);
        return ResponseEntity.ok(ApiResponse.success(categories));
    }

    /**
     * PUT /api/admin/template-standards/sort-order/bulk
     * 템플릿 정렬 순서 일괄 업데이트
     */
    @PutMapping("/sort-order/bulk")
    public ResponseEntity<ApiResponse<Void>> updateTemplateStandardSortOrder(
            @RequestBody Map<String, Object> body) {

        Object raw = body.get("templates");
        if (!(raw instanceof List)) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("templates는 배열이어야 합니다."));
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> templates = (List<Map<String, Object>>) raw;
        templateStandardService.updateTemplateStandardSortOrder(templates);

        return ResponseEntity.ok(ApiResponse.success(null, "템플릿 정렬 순서가 성공적으로 업데이트되었습니다."));
    }

    /**
     * POST /api/admin/template-standards/import
     * 템플릿 가져오기 (JSON에서)
     */
    @PostMapping("/import")
    public ResponseEntity<ApiResponse<Map<String, Object>>> importTemplateStandard(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {

        if (body.get("layout_config") == null) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("유효한 템플릿 데이터가 아닙니다."));
        }

        body.put("company_code", companyCode);
        body.put("created_by",   userId);
        body.put("updated_by",   userId);

        Map<String, Object> created = templateStandardService.insertTemplateStandard(body);
        return ResponseEntity.status(201).body(ApiResponse.success(created, "템플릿이 성공적으로 가져왔습니다."));
    }

    /**
     * GET /api/admin/template-standards/{templateCode}
     * 템플릿 상세 조회
     */
    @GetMapping("/{templateCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTemplateStandardInfo(
            @PathVariable String templateCode) {

        Map<String, Object> template = templateStandardService.getTemplateStandardInfo(templateCode);
        if (template == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("템플릿을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(template));
    }

    /**
     * GET /api/admin/template-standards/{templateCode}/export
     * 템플릿 내보내기 (메타데이터 제외 서브셋)
     */
    @GetMapping("/{templateCode}/export")
    public ResponseEntity<ApiResponse<Map<String, Object>>> exportTemplateStandard(
            @PathVariable String templateCode) {

        Map<String, Object> template = templateStandardService.getTemplateStandardInfo(templateCode);
        if (template == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("템플릿을 찾을 수 없습니다."));
        }

        // DB 결과는 camelCase (map-underscore-to-camel-case: true)
        // 응답은 Node.js 호환을 위해 snake_case 키 사용
        Map<String, Object> exportData = new LinkedHashMap<>();
        exportData.put("template_code",     template.get("template_code"));
        exportData.put("template_name",     template.get("template_name"));
        exportData.put("template_name_eng", template.get("template_name_eng"));
        exportData.put("description",       template.get("description"));
        exportData.put("category",          template.get("category"));
        exportData.put("icon_name",         template.get("icon_name"));
        exportData.put("default_size",      template.get("default_size"));
        exportData.put("layout_config",     template.get("layout_config"));

        return ResponseEntity.ok(ApiResponse.success(exportData));
    }

    /**
     * POST /api/admin/template-standards
     * 템플릿 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertTemplateStandard(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {

        if (body.get("template_code") == null || body.get("template_name") == null
                || body.get("category") == null || body.get("layout_config") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(
                    "필수 필드가 누락되었습니다. (template_code, template_name, category, layout_config)"));
        }

        body.put("company_code", companyCode);
        body.put("created_by",   userId);
        body.put("updated_by",   userId);

        Map<String, Object> created = templateStandardService.insertTemplateStandard(body);
        return ResponseEntity.status(201).body(ApiResponse.success(created, "템플릿이 성공적으로 생성되었습니다."));
    }

    /**
     * PUT /api/admin/template-standards/{templateCode}
     * 템플릿 수정
     */
    @PutMapping("/{templateCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateTemplateStandard(
            @PathVariable String templateCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {

        body.put("updated_by", userId);
        Map<String, Object> updated = templateStandardService.updateTemplateStandard(templateCode, body);
        if (updated == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("템플릿을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(updated, "템플릿이 성공적으로 수정되었습니다."));
    }

    /**
     * DELETE /api/admin/template-standards/{templateCode}
     * 템플릿 삭제
     */
    @DeleteMapping("/{templateCode}")
    public ResponseEntity<ApiResponse<Void>> deleteTemplateStandard(
            @PathVariable String templateCode) {

        boolean deleted = templateStandardService.deleteTemplateStandard(templateCode);
        if (!deleted) {
            return ResponseEntity.status(404).body(ApiResponse.error("템플릿을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "템플릿이 성공적으로 삭제되었습니다."));
    }

    /**
     * POST /api/admin/template-standards/{templateCode}/duplicate
     * 템플릿 복제
     */
    @PostMapping("/{templateCode}/duplicate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> duplicateTemplateStandard(
            @PathVariable String templateCode,
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {

        String newTemplateCode = (String) body.get("new_template_code");
        String newTemplateName = (String) body.get("new_template_name");

        if (newTemplateCode == null || newTemplateName == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("필수 필드가 누락되었습니다."));
        }

        Map<String, Object> params = new HashMap<>();
        params.put("original_code", templateCode);
        params.put("new_code",      newTemplateCode);
        params.put("new_name",      newTemplateName);
        params.put("company_code", companyCode);
        params.put("created_by",   userId);

        Map<String, Object> duplicated = templateStandardService.duplicateTemplateStandard(params);
        return ResponseEntity.status(201).body(ApiResponse.success(duplicated, "템플릿이 성공적으로 복제되었습니다."));
    }
}
