-- 创建医生患者关系表
-- 用于管理医生与患者之间的多对多关系
-- 支持主治医生、签约医生、管床医生等不同关系类型

-- 先创建序列
CREATE SEQUENCE IF NOT EXISTS "adm_practitioner_patient_id_seq"
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;

-- 再创建表
CREATE TABLE IF NOT EXISTS "adm_practitioner_patient" (
  "id" int8 NOT NULL DEFAULT nextval('adm_practitioner_patient_id_seq'::regclass),
  "practitioner_id" int8 NOT NULL,
  "patient_id" int8 NOT NULL,
  "relationship_type" int4 NOT NULL,
  "organization_id" int8 NOT NULL,
  "start_date" timestamptz(6),
  "end_date" timestamptz(6),
  "status" int4 NOT NULL DEFAULT 1,
  "remark" varchar(500),
  "tenant_id" int4,
  "delete_flag" bpchar(1) DEFAULT '0'::bpchar NOT NULL,
  "create_by" varchar(32) DEFAULT ''::varchar NOT NULL,
  "create_time" timestamptz(6) NOT NULL,
  "update_by" varchar(32),
  "update_time" timestamptz(6),
  CONSTRAINT "adm_practitioner_patient_pkey" PRIMARY KEY ("id")
);

-- 添加注释
COMMENT ON COLUMN "adm_practitioner_patient"."id" IS '主键ID';
COMMENT ON COLUMN "adm_practitioner_patient"."practitioner_id" IS '医生ID，关联adm_practitioner表';
COMMENT ON COLUMN "adm_practitioner_patient"."patient_id" IS '患者ID，关联adm_patient表';
COMMENT ON COLUMN "adm_practitioner_patient"."relationship_type" IS '关系类型：1-主治医生，2-签约医生，3-管床医生，4-家庭医生，5-会诊医生，6-随访医生';
COMMENT ON COLUMN "adm_practitioner_patient"."organization_id" IS '机构ID，关联adm_organization表';
COMMENT ON COLUMN "adm_practitioner_patient"."start_date" IS '关系开始时间';
COMMENT ON COLUMN "adm_practitioner_patient"."end_date" IS '关系结束时间';
COMMENT ON COLUMN "adm_practitioner_patient"."status" IS '状态：1-有效，0-无效';
COMMENT ON COLUMN "adm_practitioner_patient"."remark" IS '备注信息';
COMMENT ON COLUMN "adm_practitioner_patient"."tenant_id" IS '租户ID';
COMMENT ON COLUMN "adm_practitioner_patient"."delete_flag" IS '删除标志：0-未删除，1-已删除';
COMMENT ON COLUMN "adm_practitioner_patient"."create_by" IS '创建人';
COMMENT ON COLUMN "adm_practitioner_patient"."create_time" IS '创建时间';
COMMENT ON COLUMN "adm_practitioner_patient"."update_by" IS '更新人';
COMMENT ON COLUMN "adm_practitioner_patient"."update_time" IS '更新时间';
COMMENT ON TABLE "adm_practitioner_patient" IS '医生患者关系表';

-- 创建索引
CREATE INDEX IF NOT EXISTS "idx_practitioner_patient_practitioner_id" ON "adm_practitioner_patient" USING btree ("practitioner_id", "delete_flag");
CREATE INDEX IF NOT EXISTS "idx_practitioner_patient_patient_id" ON "adm_practitioner_patient" USING btree ("patient_id", "delete_flag");
CREATE INDEX IF NOT EXISTS "idx_practitioner_patient_org_id" ON "adm_practitioner_patient" USING btree ("organization_id", "delete_flag");
CREATE INDEX IF NOT EXISTS "idx_practitioner_patient_type" ON "adm_practitioner_patient" USING btree ("relationship_type", "delete_flag");

-- 插入迁移记录
INSERT INTO "__migrationshistory" ("version", "description")
VALUES ('202601020000 add_table_adm_practitioner_patient', '1.0.0');
