-- 任务统计表（2026-03-31）
-- B: 按助教+月份汇总表
-- C: 关系指数表新增历史总计字段

BEGIN;

-- ═══════════════════════════════════════════════════════════
-- B: 新建 biz.dws_assistant_task_monthly（按月汇总）
-- ═══════════════════════════════════════════════════════════

CREATE TABLE IF NOT EXISTS biz.dws_assistant_task_monthly (
    id              BIGSERIAL PRIMARY KEY,
    site_id         BIGINT NOT NULL,
    assistant_id    BIGINT NOT NULL,
    stat_month      DATE NOT NULL,  -- 月份第一天，如 2026-03-01
    -- 创建数
    recall_created          INT NOT NULL DEFAULT 0,
    follow_up_created       INT NOT NULL DEFAULT 0,
    relationship_created    INT NOT NULL DEFAULT 0,
    total_created           INT NOT NULL DEFAULT 0,
    -- 完成数
    recall_completed        INT NOT NULL DEFAULT 0,
    follow_up_completed     INT NOT NULL DEFAULT 0,
    total_completed         INT NOT NULL DEFAULT 0,
    -- 其他状态
    abandoned_count         INT NOT NULL DEFAULT 0,
    transferred_count       INT NOT NULL DEFAULT 0,
    -- 时间戳
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (site_id, assistant_id, stat_month)
);

COMMENT ON TABLE biz.dws_assistant_task_monthly IS '助教任务月度统计汇总';
COMMENT ON COLUMN biz.dws_assistant_task_monthly.stat_month IS '统计月份（月初日期）';
COMMENT ON COLUMN biz.dws_assistant_task_monthly.recall_created IS '当月创建的召回任务数（high_priority + priority）';
COMMENT ON COLUMN biz.dws_assistant_task_monthly.recall_completed IS '当月完成的召回任务数';

CREATE INDEX IF NOT EXISTS idx_task_monthly_site_month
    ON biz.dws_assistant_task_monthly (site_id, stat_month DESC);

CREATE INDEX IF NOT EXISTS idx_task_monthly_assistant
    ON biz.dws_assistant_task_monthly (assistant_id, stat_month DESC);

COMMIT;

-- ROLLBACK:
-- DROP TABLE IF EXISTS biz.dws_assistant_task_monthly;
