-- 0005_inventory_detail.sql (MySQL)
ALTER TABLE chemicals
    ADD COLUMN source                 VARCHAR(20)  NOT NULL DEFAULT 'manual',
    ADD COLUMN grocy_last_pulled_at    DATETIME     DEFAULT NULL;

CREATE TABLE IF NOT EXISTS category_mappings (
    grocy_group_id    INT PRIMARY KEY,
    display_name      VARCHAR(100)    NOT NULL,
    sort_order        INT             NOT NULL DEFAULT 0,
    created_at        DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chemical_inventory_log (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    chemical_id     VARCHAR(255)    NOT NULL,
    change_type     VARCHAR(20)     NOT NULL,
    amount_delta    DOUBLE          NOT NULL,
    amount_after    DOUBLE          DEFAULT NULL,
    source          VARCHAR(20)     NOT NULL DEFAULT 'local',
    source_ref      VARCHAR(255)    DEFAULT NULL,
    note            TEXT            DEFAULT NULL,
    occurred_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT chk_change_type CHECK (change_type IN ('purchase','consume','inventory','transfer','adjust'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE INDEX idx_invlog_chem ON chemical_inventory_log(chemical_id, occurred_at DESC);
CREATE INDEX idx_invlog_type ON chemical_inventory_log(change_type);

INSERT IGNORE INTO settings (`key`, value, is_secret, description) VALUES
    ('grocy_categories_json', '[]', 0, 'Grocy 分类映射 JSON');
