package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.provisioning.SuperAdminGuard;
import com.erp.service.CompanyManagementService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/company-management")
@RequiredArgsConstructor
@Slf4j
public class CompanyManagementController {

    private final SuperAdminGuard guard;
    private final CompanyManagementService companyManagementService;

    /**
     * DELETE /api/company-management/:companyCode
     * 회사 삭제 및 파일 정리 (soft delete)
     */
    @DeleteMapping("/{companyCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteCompany(
            HttpServletRequest request,
            @PathVariable String companyCode,
            @RequestBody(required = false) Map<String, Object> body) {

        guard.enforce(request);

        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        if (body != null) {
            params.putAll(body);
        }

        try {
            Map<String, Object> data = companyManagementService.deleteCompany(params);
            String companyName = (String) data.get("company_name");
            return ResponseEntity.ok(
                    ApiResponse.success(data, "회사 '" + companyName + "'이(가) 성공적으로 삭제되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        } catch (RuntimeException e) {
            log.error("회사 삭제 실패: companyCode={}", companyCode, e);
            return ResponseEntity.status(500).body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * GET /api/company-management/disk-usage/all
     * 전체 회사 디스크 사용량 조회
     * ※ /{companyCode}/disk-usage 보다 먼저 정의 (경로 특이성으로 충돌 없음)
     */
    @GetMapping("/disk-usage/all")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllCompaniesDiskUsage(
            HttpServletRequest request) {

        guard.enforce(request);

        try {
            Map<String, Object> data = companyManagementService.getAllCompaniesDiskUsage();
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            log.error("전체 디스크 사용량 조회 실패", e);
            return ResponseEntity.status(500).body(ApiResponse.error("전체 디스크 사용량 조회 중 오류가 발생했습니다."));
        }
    }

    /**
     * GET /api/company-management/:companyCode/disk-usage
     * 회사별 디스크 사용량 조회
     */
    @GetMapping("/{companyCode}/disk-usage")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCompanyDiskUsage(
            HttpServletRequest request,
            @PathVariable String companyCode) {

        guard.enforce(request);

        try {
            Map<String, Object> data = companyManagementService.getCompanyDiskUsage(companyCode);
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            log.error("디스크 사용량 조회 실패: companyCode={}", companyCode, e);
            return ResponseEntity.status(500).body(ApiResponse.error("디스크 사용량 조회 중 오류가 발생했습니다."));
        }
    }
}
