-- =============================================================================
-- 洗车记录系统 - Migration 0005: 资料来源 + 分类映射 + 用品详情
-- =============================================================================

-- 1. chemicals 表加资料来源 + 同步元数据
ALTER TABLE chemicals ADD COLUMN source             TEXT NOT NULL DEFAULT 'manual';
-- source: 'grocy' | 'manual' | 'seed'
ALTER TABLE chemicals ADD COLUMN grocy_last_pulled_at TEXT;

-- 2. 分类映射表（grocy_product_group_id → 真实名字）
CREATE TABLE IF NOT EXISTS category_mappings (
    grocy_group_id    INTEGER PRIMARY KEY,
    display_name      TEXT    NOT NULL,
    sort_order        INTEGER NOT NULL DEFAULT 0,
    created_at        TEXT    NOT NULL DEFAULT (datetime('now'))
);

-- 3. chemical_inventory_log 进销存记录（本地系统用）
CREATE TABLE IF NOT EXISTS chemical_inventory_log (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    chemical_id     TEXT    NOT NULL,
    change_type     TEXT    NOT NULL CHECK (change_type IN ('purchase','consume','inventory','transfer','adjust')),
    amount_delta    REAL    NOT NULL,
    amount_after    REAL,
    source          TEXT    NOT NULL DEFAULT 'local',
    -- 'local' = 本系统产生，'grocy' = 来自 Grocy
    source_ref      TEXT,
    -- 外部引用（如 Grocy stock log id、wash_record_id 等）
    note            TEXT,
    occurred_at     TEXT    NOT NULL DEFAULT (datetime('now')),
    created_at      TEXT    NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (chemical_id) REFERENCES chemicals(grocy_product_id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_invlog_chem ON chemical_inventory_log(chemical_id, occurred_at DESC);
CREATE INDEX IF NOT EXISTS idx_invlog_type ON chemical_inventory_log(change_type);

-- 4. settings seed
INSERT OR IGNORE INTO settings (key, value, is_secret, description) VALUES
    ('grocy_categories_json', '[]', 0, 'Grocy 分类 ID → 显示名映射（JSON: [{id, name}])');
