-- td_building_cell_m 楼宇小区桥接月表 DDL (标准契约版)
-- 必须与 POC-TSG...DDL(1).sql L1148-1193 100% 对齐

CREATE TABLE IF NOT EXISTS dmk.td_building_cell_m (
    year_month varchar(7) NOT NULL,
    data_type integer NOT NULL,
    building_id varchar(64) NOT NULL,
    cellkey varchar(64) NOT NULL,
    cell_name varchar(128),
    operator_name varchar(32) NOT NULL,
    network_class varchar(32) NOT NULL,
    freq varchar(32) NOT NULL DEFAULT 'all',
    indoor_flag smallint NOT NULL DEFAULT -1,
    provincecode integer,
    citycode integer,
    districtcode integer,
    cell_lon numeric(10, 6),
    cell_lat numeric(10, 6),
    cell_wkt text,
    cell_geom geometry(Point, 4326) GENERATED ALWAYS AS (
        CASE WHEN cell_wkt IS NOT NULL THEN ST_GeomFromText(cell_wkt, 4326)::geometry(Point, 4326)
             WHEN cell_lon IS NOT NULL AND cell_lat IS NOT NULL THEN ST_SetSRID(ST_MakePoint(cell_lon, cell_lat), 4326)::geometry(Point, 4326)
             ELSE NULL
        END
    ) STORED,
    updated_time timestamp without time zone NOT NULL DEFAULT now(),
    PRIMARY KEY (year_month, data_type, building_id, cellkey, operator_name, network_class, freq, indoor_flag)
);

COMMENT ON TABLE dmk.td_building_cell_m IS '楼宇小区桥接月表，支撑 /api/buildings/cells 与楼宇-小区关联。';
COMMENT ON COLUMN dmk.td_building_cell_m.year_month IS '账期，格式 YYYY-MM';
COMMENT ON COLUMN dmk.td_building_cell_m.data_type IS '数据来源类型';
COMMENT ON COLUMN dmk.td_building_cell_m.building_id IS '楼宇 ID';
COMMENT ON COLUMN dmk.td_building_cell_m.cellkey IS '小区唯一键 cellkey';
COMMENT ON COLUMN dmk.td_building_cell_m.cell_name IS '小区名称（冗余）';
COMMENT ON COLUMN dmk.td_building_cell_m.operator_name IS '运营商名称';
COMMENT ON COLUMN dmk.td_building_cell_m.network_class IS '网络制式';
COMMENT ON COLUMN dmk.td_building_cell_m.freq IS '频段';
COMMENT ON COLUMN dmk.td_building_cell_m.indoor_flag IS '室内外标识';
COMMENT ON COLUMN dmk.td_building_cell_m.provincecode IS '省编码';
COMMENT ON COLUMN dmk.td_building_cell_m.citycode IS '地市编码';
COMMENT ON COLUMN dmk.td_building_cell_m.districtcode IS '区县编码';
COMMENT ON COLUMN dmk.td_building_cell_m.cell_lon IS '小区经度';
COMMENT ON COLUMN dmk.td_building_cell_m.cell_lat IS '小区纬度';
COMMENT ON COLUMN dmk.td_building_cell_m.cell_wkt IS '小区点 WKT';
COMMENT ON COLUMN dmk.td_building_cell_m.cell_geom IS '小区点几何列（由 cell_wkt 或经纬度生成）';
COMMENT ON COLUMN dmk.td_building_cell_m.updated_time IS '记录更新时间';

CREATE INDEX IF NOT EXISTS idx_td_building_cell_query ON dmk.td_building_cell_m(year_month, data_type, provincecode, citycode, districtcode, operator_name, network_class, freq, indoor_flag);
CREATE INDEX IF NOT EXISTS idx_td_building_cell_geom ON dmk.td_building_cell_m USING gist(cell_geom) WHERE cell_geom IS NOT NULL;
