-- =============================================
-- 智慧水务管理系统 - 营收管理平台与报装管理系统增强
-- 版本: V4 (Issue #6)
-- =============================================

-- 平台运维审计日志
CREATE TABLE IF NOT EXISTS rev_audit_log (
    id BIGSERIAL PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    user_name VARCHAR(100) NOT NULL,
    action VARCHAR(50) NOT NULL,             -- CREATE/UPDATE/DELETE/LOGIN/EXPORT
    target_type VARCHAR(50),                 -- customer/meter/bill/app
    target_id VARCHAR(50),
    detail TEXT,
    ip VARCHAR(50),
    created_at TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE rev_audit_log IS '平台运维审计日志表';
CREATE INDEX IF NOT EXISTS idx_audit_user ON rev_audit_log(user_id);
CREATE INDEX IF NOT EXISTS idx_audit_action ON rev_audit_log(action);
CREATE INDEX IF NOT EXISTS idx_audit_created ON rev_audit_log(created_at);

-- 应用接入注册表
CREATE TABLE IF NOT EXISTS rev_app_registry (
    id BIGSERIAL PRIMARY KEY,
    app_id VARCHAR(50) UNIQUE NOT NULL,
    app_secret VARCHAR(100) NOT NULL,
    app_name VARCHAR(100) NOT NULL,
    redirect_uris TEXT,                      -- JSON array of redirect URIs
    enabled SMALLINT DEFAULT 1,              -- 0:disabled 1:enabled
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE rev_app_registry IS '应用接入注册表';
CREATE INDEX IF NOT EXISTS idx_app_enabled ON rev_app_registry(enabled);

-- 报装任务表
CREATE TABLE IF NOT EXISTS rev_install_task (
    id BIGSERIAL PRIMARY KEY,
    task_id VARCHAR(50) UNIQUE NOT NULL,
    apply_no VARCHAR(50) NOT NULL,
    task_type VARCHAR(50) NOT NULL,          -- design/construction/inspection
    assignee_id BIGINT,
    assignee_name VARCHAR(100),
    description TEXT,
    status VARCHAR(20) DEFAULT 'pending',    -- pending/in_progress/completed/cancelled
    remark TEXT,
    completed_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE rev_install_task IS '报装任务表';
CREATE INDEX IF NOT EXISTS idx_task_apply ON rev_install_task(apply_no);
CREATE INDEX IF NOT EXISTS idx_task_assignee ON rev_install_task(assignee_id);
CREATE INDEX IF NOT EXISTS idx_task_status ON rev_install_task(status);

-- 增强报装表（添加缺失的时间戳字段）
ALTER TABLE rev_installation ADD COLUMN IF NOT EXISTS dispatched_at TIMESTAMP;
ALTER TABLE rev_installation ADD COLUMN IF NOT EXISTS construction_started_at TIMESTAMP;
ALTER TABLE rev_installation ADD COLUMN IF NOT EXISTS customer_type VARCHAR(20);

COMMENT ON COLUMN rev_installation.dispatched_at IS '派单时间';
COMMENT ON COLUMN rev_installation.construction_started_at IS '施工开始时间';
COMMENT ON COLUMN rev_installation.customer_type IS '客户类型';
