package com.zioinfo.kintex.exhibitor;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

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

/**
 * 주최자용 참가업체 관리 조회 매퍼 — read-only.
 * booth 는 {@code layout.event_id} 경유로 행사에 귀속된다. 마이그레이션 불변.
 * 부스 배정(booth_sale)·최신 설계안(design_plan)·정산(invoice)·연락(company/event_member) 좌조인.
 */
@Mapper
public interface ExhibitorMapper {

    /** 행사명(존재 확인용). 없으면 null. */
    @Select("SELECT name FROM event WHERE id = #{eventId}")
    String findEventName(@Param("eventId") String eventId);

    /**
     * 참가업체(= 배정 부스) 목록. company 가 배정된 부스만(빈 부스 제외).
     * company/event_member 는 LATERAL LIMIT 1 로 부스당 1행을 보장(행 증식 방지).
     * 최대 500건.
     */
    @Select("""
            SELECT b.id                                   AS "boothId",
                   b.assigned_company_name                AS "companyName",
                   b.booth_no                             AS "boothNo",
                   b.booth_type                           AS "boothType",
                   ROUND(ST_Area(b.geom)::numeric, 1)     AS "areaM2",
                   bs.status                              AS "saleStatus",
                   COALESCE(dp.status, 'draft')           AS "designStatus",
                   inv.status                             AS "invoiceStatus",
                   COALESCE(inv.total - inv.paid_amount, 0) AS "outstanding",
                   mem.display_name                       AS "contactName",
                   co.phone                               AS "contactPhone"
            FROM booth b
            JOIN layout l ON l.id = b.layout_id
            LEFT JOIN booth_sale bs
                   ON bs.booth_id = b.id AND bs.event_id = l.event_id
            LEFT JOIN LATERAL (
                SELECT d.status FROM design_plan d
                WHERE d.booth_id = b.id ORDER BY d.version DESC LIMIT 1
            ) dp ON true
            LEFT JOIN invoice inv
                   ON inv.event_id = l.event_id AND inv.exhibitor_name = b.assigned_company_name
            LEFT JOIN LATERAL (
                SELECT au.display_name
                FROM event_member em
                JOIN app_user au ON au.id = em.user_id
                WHERE em.event_id = l.event_id AND em.booth_id = b.id AND em.role_code = 'EXHIBITOR'
                LIMIT 1
            ) mem ON true
            LEFT JOIN LATERAL (
                SELECT c.phone FROM company c
                WHERE c.name = b.assigned_company_name LIMIT 1
            ) co ON true
            WHERE l.event_id = #{eventId}
              AND b.assigned_company_name IS NOT NULL
            ORDER BY b.booth_no NULLS LAST
            LIMIT 500
            """)
    List<Map<String, Object>> findExhibitors(@Param("eventId") String eventId);
}
