-- 킨텍스 — 공간 코어 스키마 (PLANNING §8: 부스 POLYGON·트렌치 POINT·배선 LINESTRING)
-- SRID 0 = 홀 로컬 평면 좌표계(미터). ST_Area/ST_Distance/ST_Length 결과 단위 = m/㎡.
-- 공간 인덱스는 전부 GiST.

-- 트렌치 (POINT) — 유틸리티 공급 매트릭스(홀1·7 가스) ------------------------
CREATE TABLE IF NOT EXISTS trench (
    id             varchar(60)      PRIMARY KEY,
    hall_id        varchar(20)      NOT NULL REFERENCES hall(id) ON DELETE CASCADE,
    geom           geometry(Point,0) NOT NULL,
    supply_power   boolean          NOT NULL DEFAULT true,
    supply_water   boolean          NOT NULL DEFAULT true,
    supply_air     boolean          NOT NULL DEFAULT true,
    supply_network boolean          NOT NULL DEFAULT true,
    supply_gas     boolean          NOT NULL DEFAULT false,
    is_assumed     boolean          NOT NULL DEFAULT true   -- 실측 아닌 가정 그리드(PLANNING R4)
);
CREATE INDEX IF NOT EXISTS idx_trench_geom ON trench USING GIST (geom);
CREATE INDEX IF NOT EXISTS idx_trench_hall ON trench (hall_id);

-- 비상구 (POINT + 이격 버퍼) — 비상구 차단 검증(ST_Intersects) ---------------
CREATE TABLE IF NOT EXISTS hall_exit (
    id          varchar(60)      PRIMARY KEY,
    hall_id     varchar(20)      NOT NULL REFERENCES hall(id) ON DELETE CASCADE,
    geom        geometry(Point,0) NOT NULL,
    clearance_m numeric(5,2)     NOT NULL DEFAULT 3.0,   -- 비상구 접근 확보 버퍼(m)
    is_assumed  boolean          NOT NULL DEFAULT true
);
CREATE INDEX IF NOT EXISTS idx_hall_exit_geom ON hall_exit USING GIST (geom);

-- 배치안 (Layout, 버전) ------------------------------------------------------
CREATE TABLE IF NOT EXISTS layout (
    id         varchar(40) PRIMARY KEY,
    event_id   varchar(40) NOT NULL REFERENCES event(id) ON DELETE CASCADE,
    hall_id    varchar(20) NOT NULL REFERENCES hall(id),
    version    integer     NOT NULL DEFAULT 1,
    name       varchar(120),
    status     varchar(20) NOT NULL DEFAULT 'draft',
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now(),
    UNIQUE (event_id, hall_id, version)
);

-- 부스 (POLYGON) -------------------------------------------------------------
CREATE TABLE IF NOT EXISTS booth (
    id                    varchar(40)        PRIMARY KEY,
    layout_id             varchar(40)        NOT NULL REFERENCES layout(id) ON DELETE CASCADE,
    booth_no              varchar(40),
    booth_type            varchar(20),       -- assembled|independent|corner|island
    geom                  geometry(Polygon,0) NOT NULL,
    size_w_m              numeric(8,2),
    size_d_m              numeric(8,2),
    height_m              numeric(6,2),      -- 규정 HEIGHT_MAX 대상
    floor_load_t_per_m2   numeric(5,2),      -- 규정 FLOOR_LOAD 대상
    assigned_company_name varchar(200),      -- 표시용(민감정보 아님)
    premium               boolean            NOT NULL DEFAULT false,
    created_at            timestamptz        NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_booth_geom   ON booth USING GIST (geom);
CREATE INDEX IF NOT EXISTS idx_booth_layout ON booth (layout_id);

-- 부스 설계안 (DesignPlan 버전, spec jsonb) ----------------------------------
CREATE TABLE IF NOT EXISTS design_plan (
    id         varchar(40) PRIMARY KEY,
    booth_id   varchar(40) NOT NULL REFERENCES booth(id) ON DELETE CASCADE,
    version    integer     NOT NULL DEFAULT 1,
    status     varchar(20) NOT NULL DEFAULT 'draft',
    spec       jsonb,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now(),
    UNIQUE (booth_id, version)
);

-- 유틸리티 신청 (UtilityOrder, 배선 LINESTRING) ------------------------------
-- booth_id는 배치 재저장(replaceBooths) 시 부스 교체 가능성 때문에 소프트 참조(FK 미설정).
CREATE TABLE IF NOT EXISTS utility_order (
    id                   varchar(40) PRIMARY KEY,
    event_id             varchar(40) NOT NULL REFERENCES event(id) ON DELETE CASCADE,
    booth_id             varchar(40) NOT NULL,
    status               varchar(20) NOT NULL DEFAULT 'submitted',
    quote                jsonb,
    wiring               geometry(MultiLineString,0),   -- 전기/네트워크/급배수 배선 경로
    location_diagram_url varchar(300),                  -- 자동 생성 위치표시도(M4-3)
    supply_timing        varchar(120),
    created_at           timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_utility_order_wiring ON utility_order USING GIST (wiring);
CREATE INDEX IF NOT EXISTS idx_utility_order_booth  ON utility_order (booth_id);

-- 렌더잡 (RenderJob, 이력·쿼터 정본) -----------------------------------------
-- event_id/booth_id 소프트 참조(감사·쿼터 이력은 부스 교체와 무관하게 보존).
CREATE TABLE IF NOT EXISTS render_job (
    id            varchar(40) PRIMARY KEY,
    event_id      varchar(40) NOT NULL,
    booth_id      varchar(40) NOT NULL,
    shot_preset   varchar(10) NOT NULL,     -- S1..S7
    status        varchar(12) NOT NULL DEFAULT 'QUEUED',  -- QUEUED|RUNNING|DONE|FAILED
    image_url     varchar(300),
    schema_hash   varchar(80),
    model_version varchar(60),
    error_message varchar(300),             -- 사용자 친화 요약만(스택트레이스 금지)
    created_at    timestamptz NOT NULL DEFAULT now(),
    updated_at    timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_render_job_booth        ON render_job (booth_id, shot_preset);
CREATE INDEX IF NOT EXISTS idx_render_job_event_status ON render_job (event_id, status);
