-- Issue #87: 巡查设置（区域/路线/表单/模版）

-- PAT-16: 巡检区域
CREATE TABLE IF NOT EXISTS patrol_area (
    id              BIGSERIAL PRIMARY KEY,
    name            VARCHAR(100) NOT NULL,
    code            VARCHAR(50) UNIQUE,
    parent_id       BIGINT DEFAULT 0,
    description     TEXT,
    lng             DOUBLE PRECISION,
    lat             DOUBLE PRECISION,
    radius          DOUBLE PRECISION DEFAULT 0,
    status          VARCHAR(20) DEFAULT 'active',
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_patrol_area_parent ON patrol_area(parent_id);

-- PAT-17: 巡检路线扩展
-- patrol_route 已在 V1__production.sql 创建，此处补充缺失字段
ALTER TABLE patrol_route ADD COLUMN IF NOT EXISTS area_id BIGINT;
ALTER TABLE patrol_route ADD COLUMN IF NOT EXISTS description TEXT;
ALTER TABLE patrol_route ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW();

-- 巡检路线巡检点
CREATE TABLE IF NOT EXISTS patrol_route_checkpoint (
    id              BIGSERIAL PRIMARY KEY,
    route_id        BIGINT NOT NULL,
    checkpoint_seq  INT NOT NULL,
    device_id       BIGINT,
    device_name     VARCHAR(100),
    lng             DOUBLE PRECISION,
    lat             DOUBLE PRECISION,
    check_items     TEXT,  -- JSON array
    created_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_route_checkpoint ON patrol_route_checkpoint(route_id);

-- PAT-18: 自定义巡检表单
CREATE TABLE IF NOT EXISTS patrol_form (
    id              BIGSERIAL PRIMARY KEY,
    name            VARCHAR(100) NOT NULL,
    type            VARCHAR(30) NOT NULL,  -- daily/special/safety/quality
    fields          TEXT NOT NULL,          -- JSON array of field definitions
    status          VARCHAR(20) DEFAULT 'active',
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);

-- PAT-19: 表单绑定关系
CREATE TABLE IF NOT EXISTS patrol_form_binding (
    id              BIGSERIAL PRIMARY KEY,
    form_id         BIGINT NOT NULL,
    target_type     VARCHAR(20) NOT NULL,  -- route/device/area
    target_id       BIGINT NOT NULL,
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(form_id, target_type, target_id)
);
CREATE INDEX IF NOT EXISTS idx_form_binding_target ON patrol_form_binding(target_type, target_id);

-- PAT-20: 巡检模板
CREATE TABLE IF NOT EXISTS patrol_template (
    id              BIGSERIAL PRIMARY KEY,
    name            VARCHAR(100) NOT NULL,
    type            VARCHAR(20) NOT NULL,  -- daily/weekly/monthly/special
    config          TEXT NOT NULL,          -- JSON: frequency, routes, workers, schedule
    status          VARCHAR(20) DEFAULT 'active',
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);
