-- T004: 扩展天道系统 - 因果值/功德值/业力值系统
-- 对齐GDD-02 13.5.5 因果系统 + T003审阅报告

-- 1. 创建因果系统表
CREATE TABLE IF NOT EXISTS karma_records (
    id              BIGSERIAL PRIMARY KEY,
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    karma_type      VARCHAR(16) NOT NULL, -- good_evil/bonus/penalty
    karma_value     INT NOT NULL, -- 正数=善因，负数=恶因
    reason_code     VARCHAR(64) NOT NULL,
    related_id      UUID, -- 关联的事件/战斗/任务ID
    world_tier      SMALLINT NOT NULL,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_karma_character ON karma_records(character_id, created_at);
CREATE INDEX idx_karma_type ON karma_records(karma_type, created_at);
COMMENT ON TABLE karma_records IS '因果记录表，记录玩家行为的因果关系';

-- 2. 创建因果轮回事件表
CREATE TABLE IF NOT EXISTS karma_events (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    event_type      VARCHAR(32) NOT NULL, -- good_tribute/bad_retribution
    trigger_value   INT NOT NULL, -- 触发时的因果值
    event_data      JSONB NOT NULL DEFAULT '{}',
    status          VARCHAR(16) NOT NULL DEFAULT 'pending', -- pending/completed/failed
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    completed_at    TIMESTAMPTZ
);

CREATE INDEX idx_karma_events_character ON karma_events(character_id, status);

-- 3. 扩展characters表字段（已在003中添加部分，这里补充）
-- 因果值字段（GDD-02 13.5.5）
ALTER TABLE characters ADD COLUMN IF NOT EXISTS karma_good INT NOT NULL DEFAULT 0; -- 善因积累
ALTER TABLE characters ADD COLUMN IF NOT EXISTS karma_evil INT NOT NULL DEFAULT 0; -- 恶因积累
ALTER TABLE characters ADD COLUMN IF NOT EXISTS karma_balance NUMERIC(10,2) NOT NULL DEFAULT 0; -- 因果平衡值

-- 4. 创建功德消耗记录表
CREATE TABLE IF NOT EXISTS karma_expenditure_records (
    id              BIGSERIAL PRIMARY KEY,
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    expenditure_type VARCHAR(32) NOT NULL, -- offset_sin/protect/buff/reward
    amount          INT NOT NULL,
    related_id      UUID,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_karma_expend_character ON karma_expenditure_records(character_id, created_at);

-- 5. 创建功德护体效果表
CREATE TABLE IF NOT EXISTS karma_shields (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    shield_type     VARCHAR(32) NOT NULL, -- life_save/breakthrough_buff/luck_boost
    trigger_condition JSONB NOT NULL DEFAULT '{}',
    effect_data     JSONB NOT NULL DEFAULT '{}',
    is_active       BOOLEAN NOT NULL DEFAULT true,
    uses_remaining  SMALLINT NOT NULL DEFAULT 1,
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    expires_at      TIMESTAMPTZ
);

CREATE INDEX idx_karma_shields_character ON karma_shields(character_id, is_active);

-- 6. 创建功德馈赠事件表
CREATE TABLE IF NOT EXISTS karma_gifts (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    gift_type       VARCHAR(32) NOT NULL, -- fortune_favor/rare_opportunity/special_event
    gift_data       JSONB NOT NULL DEFAULT '{}',
    is_claimed      BOOLEAN NOT NULL DEFAULT false,
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    expires_at      TIMESTAMPTZ
);

CREATE INDEX idx_karma_gifts_character ON karma_gifts(character_id, is_claimed);

-- 7. 创建业力累积记录表（GDD-04 秘术系统）
CREATE TABLE IF NOT EXISTS sin_accumulation (
    id              BIGSERIAL PRIMARY KEY,
    character_id    UUID NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    source_type     VARCHAR(32) NOT NULL, -- forbidden_art/killing/betrayal/special_event
    sin_amount      INT NOT NULL,
    reason_code     VARCHAR(64) NOT NULL,
    related_id      UUID,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_sin_accumulation_character ON sin_accumulation(character_id, created_at);

-- 8. 插入因果轮回事件配置
INSERT INTO manual_types (id, name, description, max_equipped, acquisition_req, usage_cost, cooldown_config, conflict_rules) VALUES
('karma_event_good', '善因轮回事件', '因果值达到极端值时触发的善报事件', 0,
 '{"min_karma_good":1000}',
 '{"type":"tribute"}',
 '{"min_interval_hours":168}',
 '[]'),
('karma_event_evil', '恶因轮回事件', '因果值达到极端值时触发的恶报事件', 0,
 '{"min_karma_evil":-1000}',
 '{"type":"retribution"}',
 '{"min_interval_hours":168}',
 '[]')
ON CONFLICT (id) DO NOTHING;

-- 9. 创建天道馈赠触发条件配置表
CREATE TABLE IF NOT EXISTS karma_gift_conditions (
    id              SERIAL PRIMARY KEY,
    condition_type  VARCHAR(32) NOT NULL,
    threshold_value INT NOT NULL,
    gift_type       VARCHAR(32) NOT NULL,
    gift_data       JSONB NOT NULL DEFAULT '{}',
    probability     NUMERIC(5,4) NOT NULL DEFAULT 1.0,
    cooldown_hours  INT NOT NULL DEFAULT 168,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

INSERT INTO karma_gift_conditions (condition_type, threshold_value, gift_type, gift_data, probability, cooldown_hours) VALUES
('karma_good', 100, 'breakthrough_buff', '{"success_rate_bonus":0.05,"description":"天道庇护：境界突破成功率+5%"}', 1.0, 720),
('karma_good', 500, 'luck_boost', '{"fortune_trigger_rate":0.10,"description":"天命相助：游历机缘触发概率+10%"}', 1.0, 720),
('karma_good', 1000, 'appearance_buff', '{"appearance":"功德身","heavenly_tribulation_reduce":1,"description":"功德圆满：获得功德身外观；渡劫时减少1次天劫"}', 1.0, 720),
('karma_good', 2000, 'rare_opportunity', '{"rare_event_chance":0.05,"description":"天道认可：极小概率获得天道馈赠机缘"}', 0.05, 720);
