package com.zioinfo.kintex.exhibitor;

import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import com.zioinfo.kintex.exhibitor.dto.ExhibitorListDto;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 주최자용 참가업체 관리 서비스 — 실 테이블 집계로 목록·요약을 조립.
 * 부스에 배정된 참가업체만 반환한다(빈 부스 제외). 데이터가 없으면 빈 목록(정직).
 */
@Service
public class ExhibitorService {

    private final ExhibitorMapper mapper;

    public ExhibitorService(ExhibitorMapper mapper) {
        this.mapper = mapper;
    }

    public ExhibitorListDto list(String eventId) {
        String eventName = mapper.findEventName(eventId);
        if (eventName == null) {
            throw new ApiException(ErrorCode.NOT_FOUND, "행사를 찾을 수 없습니다.");
        }
        List<ExhibitorListDto.Row> rows = buildRows(mapper.findExhibitors(eventId));
        return new ExhibitorListDto(eventId, eventName, buildSummary(rows), rows);
    }

    private List<ExhibitorListDto.Row> buildRows(List<Map<String, Object>> src) {
        List<ExhibitorListDto.Row> out = new ArrayList<>();
        if (src == null) {
            return out;
        }
        for (Map<String, Object> r : src) {
            out.add(new ExhibitorListDto.Row(
                    str(r.get("boothId")),
                    str(r.get("companyName")),
                    str(r.get("boothNo")),
                    str(r.get("boothType")),
                    dbl(r.get("areaM2")),
                    str(r.get("saleStatus")),
                    str(r.get("designStatus")),
                    str(r.get("invoiceStatus")),
                    lng(r.get("outstanding")),
                    str(r.get("contactName")),
                    str(r.get("contactPhone"))));
        }
        return out;
    }

    private ExhibitorListDto.Summary buildSummary(List<ExhibitorListDto.Row> rows) {
        int contracted = 0;
        int designApproved = 0;
        int settlementPaid = 0;
        int outstandingCount = 0;
        for (ExhibitorListDto.Row r : rows) {
            if ("sold".equals(r.saleStatus())) {
                contracted++;
            }
            if ("approved".equals(r.designStatus())) {
                designApproved++;
            }
            if ("paid".equals(r.invoiceStatus())) {
                settlementPaid++;
            }
            if (r.outstanding() > 0) {
                outstandingCount++;
            }
        }
        return new ExhibitorListDto.Summary(rows.size(), contracted, designApproved, settlementPaid, outstandingCount);
    }

    private static Double dbl(Object o) {
        if (o == null) return null;
        if (o instanceof Number n) return n.doubleValue();
        try {
            return Double.parseDouble(String.valueOf(o));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private static long lng(Object o) {
        if (o == null) return 0L;
        if (o instanceof Number n) return n.longValue();
        try {
            return Long.parseLong(String.valueOf(o));
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    private static String str(Object o) {
        return o == null ? null : String.valueOf(o);
    }
}
