-- Description: 数据库初始化脚本
-- CREATE ROLE maptile WITH LOGIN PASSWORD 'maptile_passwd';
-- CREATE DATABASE maptile WITH OWNER maptile;

-- Postgis extension
CREATE EXTENSION IF NOT EXISTS postgis;

-- UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- 地图数据状态
CREATE TYPE feature_status AS ENUM ('normal', 'banned', 'deleted');
COMMENT ON TYPE feature_status IS '地图数据状态枚举类型，包括正常、未激活、封禁和删除';

-- 地图相关数据
CREATE TABLE feature (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name TEXT NOT NULL,
  geometry Geometry(Geometry, 4326),
  status feature_status NOT NULL DEFAULT 'normal',
  created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
  updated_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())
);
COMMENT ON COLUMN feature.id IS '地图ID';
COMMENT ON COLUMN feature.name IS '地图名称';
COMMENT ON COLUMN feature.geometry IS '地图几何数据';
COMMENT ON COLUMN feature.created_at IS '创建时间';
COMMENT ON COLUMN feature.updated_at IS '更新时间';

-- 标签数据
CREATE TABLE tag (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
  updated_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())
);
COMMENT ON COLUMN tag.id IS '标签ID';
COMMENT ON COLUMN tag.name IS '标签名称';
COMMENT ON COLUMN tag.created_at IS '创建时间';
COMMENT ON COLUMN tag.updated_at IS '更新时间';

-- 地图标签关联表
CREATE TABLE feature_tag (
  feature_id UUID NOT NULL,
  tag_id INTEGER NOT NULL,
  created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
  updated_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
  UNIQUE (feature_id, tag_id)
);
COMMENT ON COLUMN feature_tag.feature_id IS '地图ID';
COMMENT ON COLUMN feature_tag.tag_id IS '标签ID';
COMMENT ON COLUMN feature_tag.created_at IS '创建时间';
COMMENT ON COLUMN feature_tag.updated_at IS '更新时间';