-- 户外招聘会展位副本：招聘会绑定场地后，在招聘会详情内独立生成和维护展位图
-- 瀚高数据库 / PostgreSQL 兼容

CREATE SEQUENCE IF NOT EXISTS "cms_outdoor_fair_booth_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;

CREATE TABLE IF NOT EXISTS "cms_outdoor_fair_booth" (
    "id" BIGINT NOT NULL DEFAULT nextval('"cms_outdoor_fair_booth_id_seq"') PRIMARY KEY,
    "fair_id" BIGINT NOT NULL,
    "source_venue_id" BIGINT,
    "source_booth_id" BIGINT,
    "booth_number" VARCHAR(50) NOT NULL,
    "position_x" INTEGER NOT NULL DEFAULT 0,
    "position_y" INTEGER NOT NULL DEFAULT 0,
    "create_by" VARCHAR(64) DEFAULT '',
    "create_time" TIMESTAMP(0),
    "update_by" VARCHAR(64) DEFAULT '',
    "update_time" TIMESTAMP(0),
    "remark" VARCHAR(500),
    "del_flag" CHAR(1) DEFAULT '0'
);

COMMENT ON TABLE "cms_outdoor_fair_booth" IS '户外招聘会展位图副本';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."fair_id" IS '招聘会ID';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."source_venue_id" IS '来源场地ID';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."source_booth_id" IS '来源场地展位ID';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."booth_number" IS '展位号';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."position_x" IS 'X坐标';
COMMENT ON COLUMN "cms_outdoor_fair_booth"."position_y" IS 'Y坐标';

CREATE UNIQUE INDEX IF NOT EXISTS "uk_cms_outdoor_fair_booth_number" ON "cms_outdoor_fair_booth" ("fair_id", "booth_number");
CREATE INDEX IF NOT EXISTS "idx_cms_outdoor_fair_booth_fair" ON "cms_outdoor_fair_booth" ("fair_id");

-- 兼容历史预定：如果已有副本保留了 source_booth_id，把旧 booking.booth_id 改为招聘会副本展位ID
UPDATE "cms_outdoor_fair_booth_booking" booking
SET "booth_id" = fair_booth."id",
    "booth_number" = fair_booth."booth_number"
FROM "cms_outdoor_fair_booth" fair_booth
WHERE booking."fair_id" = fair_booth."fair_id"
  AND booking."booth_id" = fair_booth."source_booth_id"
  AND booking."del_flag" = '0'
  AND NOT EXISTS (
      SELECT 1
      FROM "cms_outdoor_fair_booth" snapshot_booth
      WHERE snapshot_booth."fair_id" = booking."fair_id"
        AND snapshot_booth."id" = booking."booth_id"
  );
