-- Unified quote journal: single append-only table for all price quotes.
-- Replaces the three separate log tables (stock_log, partnumber_log_competitors, lot_log)
-- as the source for pricelist generation. Old tables remain as read-only archives.
CREATE TABLE IF NOT EXISTS parts_log (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    -- Source (FK to supplier.supplier_code)
    supplier_code   VARCHAR(100) NOT NULL DEFAULT ''
        COMMENT 'FK to supplier.supplier_code',

    -- Item
    partnumber      VARCHAR(255) NOT NULL DEFAULT ''
        COMMENT 'Raw p/n; for lot_log rows partnumber=lot_name (frozen, do not overwrite)',
    vendor          VARCHAR(255) NOT NULL DEFAULT '',
    description     VARCHAR(1000) NULL,

    -- Lot mapping (denormalized, filled by backfill job)
    lot_name        VARCHAR(255) NULL
        COMMENT 'NULL until backfill. For lot_log rows filled immediately (partnumber=lot_name)',
    lot_category    VARCHAR(50)  NULL
        COMMENT 'Snapshot of lot.lot_category at resolution time',

    -- Price (always USD — convert before inserting)
    price           DECIMAL(12,4) NOT NULL,
    qty             DECIMAL(12,4) NULL
        COMMENT 'NULL if not specified in the file (not equal to 0)',

    -- Offer parameters
    offer_type      ENUM('private','public') NOT NULL DEFAULT 'public',
    lead_time_weeks INT NULL
        COMMENT 'Lead time in weeks. NULL=not specified (not equal to 0)',

    -- Audit
    created_by      VARCHAR(100) NOT NULL DEFAULT ''
        COMMENT 'MySQL username or UI username',
    quote_date      DATE NOT NULL
        COMMENT 'Quote date: from UI → from file → today',
    created_at      TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT fk_parts_log_supplier
        FOREIGN KEY (supplier_code) REFERENCES supplier(supplier_code)
        ON UPDATE CASCADE ON DELETE RESTRICT,

    UNIQUE INDEX uq_pl_src_pn_date (supplier_code, partnumber(191), quote_date),
    INDEX idx_pl_supplier_date  (supplier_code, quote_date),
    INDEX idx_pl_partnumber     (partnumber(191)),
    INDEX idx_pl_lot_name_date  (lot_name, quote_date),
    INDEX idx_pl_lot_null       (lot_name, supplier_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
