CREATE TABLE IF NOT EXISTS tenant_configs (
  tenant_id      VARCHAR(50) PRIMARY KEY,
  tenant_name    VARCHAR(100) NOT NULL,
  db_host        VARCHAR(100) NOT NULL DEFAULT '127.0.0.1',
  db_port        INTEGER NOT NULL,
  db_name        VARCHAR(100) NOT NULL DEFAULT 'bill_query',
  db_user        VARCHAR(50) DEFAULT 'postgres',
  db_password    VARCHAR(100) DEFAULT '',
  frp_port       INTEGER NOT NULL,
  status         VARCHAR(20) DEFAULT 'inactive',
  created_at     TIMESTAMP DEFAULT NOW(),
  updated_at     TIMESTAMP DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS tenant_users (
  id         SERIAL PRIMARY KEY,
  tenant_id  VARCHAR(50) REFERENCES tenant_configs(tenant_id) ON DELETE CASCADE,
  username   VARCHAR(50) NOT NULL,
  password   VARCHAR(200) NOT NULL,
  role       VARCHAR(20) NOT NULL,
  name       VARCHAR(50),
  store_code VARCHAR(20),
  region     VARCHAR(500),
  dept       VARCHAR(50),
  is_active  BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT NOW(),
  UNIQUE(tenant_id, username)
);

CREATE TABLE IF NOT EXISTS platform_admins (
  id         SERIAL PRIMARY KEY,
  username   VARCHAR(50) UNIQUE NOT NULL,
  password   VARCHAR(200) NOT NULL,
  name       VARCHAR(50) NOT NULL
);

INSERT INTO platform_admins (username, password, name) VALUES ('平台管理员', '123', '平台管理员') ON CONFLICT DO NOTHING;

INSERT INTO tenant_configs (tenant_id, tenant_name, db_port, frp_port, status) VALUES ('tenant_a', '默认租户', 15432, 15432, 'active') ON CONFLICT DO NOTHING;
