-- =============================================================================
-- zqyy_app / biz（核心业务表（任务/备注/触发器））
-- 生成日期：2026-03-15
-- 来源：测试库（通过脚本自动导出）
-- =============================================================================

CREATE SCHEMA IF NOT EXISTS biz;

-- 序列
CREATE SEQUENCE IF NOT EXISTS biz.ai_cache_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.ai_conversations_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.ai_messages_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.coach_task_history_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.coach_tasks_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.notes_id_seq AS bigint;
CREATE SEQUENCE IF NOT EXISTS biz.trigger_jobs_id_seq AS integer;

-- 表
CREATE TABLE biz.ai_cache (
    id bigint DEFAULT nextval('biz.ai_cache_id_seq'::regclass) NOT NULL,
    cache_type character varying(30) NOT NULL,
    site_id bigint NOT NULL,
    target_id character varying(100) NOT NULL,
    result_json jsonb NOT NULL,
    score integer,
    triggered_by character varying(100),
    created_at timestamp with time zone DEFAULT now() NOT NULL,
    expires_at timestamp with time zone
);

CREATE TABLE biz.ai_conversations (
    id bigint DEFAULT nextval('biz.ai_conversations_id_seq'::regclass) NOT NULL,
    user_id character varying(50) NOT NULL,
    nickname character varying(100) DEFAULT ''::character varying NOT NULL,
    app_id character varying(30) NOT NULL,
    site_id bigint NOT NULL,
    source_page character varying(100),
    source_context jsonb,
    created_at timestamp with time zone DEFAULT now() NOT NULL
);

CREATE TABLE biz.ai_messages (
    id bigint DEFAULT nextval('biz.ai_messages_id_seq'::regclass) NOT NULL,
    conversation_id bigint NOT NULL,
    role character varying(10) NOT NULL,
    content text NOT NULL,
    tokens_used integer,
    created_at timestamp with time zone DEFAULT now() NOT NULL
);

CREATE TABLE biz.coach_task_history (
    id bigint DEFAULT nextval('biz.coach_task_history_id_seq'::regclass) NOT NULL,
    task_id bigint NOT NULL,
    action character varying(50) NOT NULL,
    old_status character varying(20),
    new_status character varying(20),
    old_task_type character varying(50),
    new_task_type character varying(50),
    detail jsonb,
    created_at timestamp with time zone DEFAULT now()
);

CREATE TABLE biz.coach_tasks (
    id bigint DEFAULT nextval('biz.coach_tasks_id_seq'::regclass) NOT NULL,
    site_id bigint NOT NULL,
    assistant_id bigint NOT NULL,
    member_id bigint NOT NULL,
    task_type character varying(50) NOT NULL,
    status character varying(20) DEFAULT 'active'::character varying NOT NULL,
    priority_score numeric(5,2),
    expires_at timestamp with time zone,
    is_pinned boolean DEFAULT false,
    abandon_reason text,
    completed_at timestamp with time zone,
    completed_task_type character varying(50),
    parent_task_id bigint,
    created_at timestamp with time zone DEFAULT now(),
    updated_at timestamp with time zone DEFAULT now()
);

CREATE TABLE biz.notes (
    id bigint DEFAULT nextval('biz.notes_id_seq'::regclass) NOT NULL,
    site_id bigint NOT NULL,
    user_id integer NOT NULL,
    target_type character varying(50) NOT NULL,
    target_id bigint NOT NULL,
    type character varying(20) DEFAULT 'normal'::character varying NOT NULL,
    content text NOT NULL,
    rating_service_willingness smallint,
    rating_revisit_likelihood smallint,
    task_id bigint,
    ai_score smallint,
    ai_analysis text,
    created_at timestamp with time zone DEFAULT now(),
    updated_at timestamp with time zone DEFAULT now(),
    score smallint
);

CREATE TABLE biz.trigger_jobs (
    id integer DEFAULT nextval('biz.trigger_jobs_id_seq'::regclass) NOT NULL,
    job_type character varying(100) NOT NULL,
    job_name character varying(100) NOT NULL,
    trigger_condition character varying(20) NOT NULL,
    trigger_config jsonb NOT NULL,
    last_run_at timestamp with time zone,
    next_run_at timestamp with time zone,
    status character varying(20) DEFAULT 'enabled'::character varying NOT NULL,
    created_at timestamp with time zone DEFAULT now()
);

-- 约束（主键 / 唯一 / 外键）
ALTER TABLE biz.ai_cache ADD CONSTRAINT ai_cache_pkey PRIMARY KEY (id);
ALTER TABLE biz.ai_conversations ADD CONSTRAINT ai_conversations_pkey PRIMARY KEY (id);
ALTER TABLE biz.ai_messages ADD CONSTRAINT ai_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES biz.ai_conversations(id) ON DELETE CASCADE;
ALTER TABLE biz.ai_messages ADD CONSTRAINT ai_messages_pkey PRIMARY KEY (id);
ALTER TABLE biz.coach_task_history ADD CONSTRAINT coach_task_history_task_id_fkey FOREIGN KEY (task_id) REFERENCES biz.coach_tasks(id);
ALTER TABLE biz.coach_task_history ADD CONSTRAINT coach_task_history_pkey PRIMARY KEY (id);
ALTER TABLE biz.coach_tasks ADD CONSTRAINT coach_tasks_parent_task_id_fkey FOREIGN KEY (parent_task_id) REFERENCES biz.coach_tasks(id);
ALTER TABLE biz.coach_tasks ADD CONSTRAINT coach_tasks_pkey PRIMARY KEY (id);
ALTER TABLE biz.notes ADD CONSTRAINT notes_task_id_fkey FOREIGN KEY (task_id) REFERENCES biz.coach_tasks(id);
ALTER TABLE biz.notes ADD CONSTRAINT notes_pkey PRIMARY KEY (id);
ALTER TABLE biz.trigger_jobs ADD CONSTRAINT trigger_jobs_pkey PRIMARY KEY (id);
ALTER TABLE biz.trigger_jobs ADD CONSTRAINT trigger_jobs_job_name_key UNIQUE (job_name);

-- 索引
CREATE INDEX idx_ai_cache_cleanup ON biz.ai_cache USING btree (cache_type, site_id, target_id, created_at);
CREATE INDEX idx_ai_cache_lookup ON biz.ai_cache USING btree (cache_type, site_id, target_id, created_at DESC);
CREATE INDEX idx_ai_conv_app_site ON biz.ai_conversations USING btree (app_id, site_id, created_at DESC);
CREATE INDEX idx_ai_conv_user_site ON biz.ai_conversations USING btree (user_id, site_id, created_at DESC);
CREATE INDEX idx_ai_msg_conv ON biz.ai_messages USING btree (conversation_id, created_at);
CREATE INDEX idx_coach_tasks_assistant_status ON biz.coach_tasks USING btree (site_id, assistant_id, status);
CREATE UNIQUE INDEX idx_coach_tasks_site_assistant_member_type ON biz.coach_tasks USING btree (site_id, assistant_id, member_id, task_type) WHERE ((status)::text = 'active'::text);
CREATE INDEX idx_notes_target ON biz.notes USING btree (site_id, target_type, target_id);



-- =============================================================================
-- 种子数据：触发器配置（4 条）
-- =============================================================================

INSERT INTO biz.trigger_jobs (job_type, job_name, trigger_condition, trigger_config, next_run_at)
VALUES
    ('task_generator', 'task_generator', 'cron',
     '{"cron_expression": "0 7 * * *"}',
     (CURRENT_DATE + 1) + INTERVAL '7 hours'),
    ('task_expiry_check', 'task_expiry_check', 'interval',
     '{"interval_seconds": 3600}',
     NOW() + INTERVAL '1 hour'),
    ('recall_completion_check', 'recall_completion_check', 'event',
     '{"event_name": "etl_data_updated"}',
     NULL),
    ('note_reclassify_backfill', 'note_reclassify_backfill', 'event',
     '{"event_name": "recall_completed"}',
     NULL)
ON CONFLICT (job_name) DO NOTHING;
