-- v3.1 Inventory Vehicle Compatibility
-- Links local inventory items to vehicles for Local catalog browsing.

CREATE TABLE IF NOT EXISTS inventory_vehicle_compat (
    id SERIAL PRIMARY KEY,
    inventory_id INTEGER NOT NULL REFERENCES inventory(id) ON DELETE CASCADE,
    model_year_engine_id INTEGER NOT NULL,
    source VARCHAR(20) DEFAULT 'manual', -- 'auto_match', 'manual', 'import'
    confidence NUMERIC(4,3) DEFAULT 1.0, -- auto-match confidence (0-1)
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(inventory_id, model_year_engine_id)
);

CREATE INDEX IF NOT EXISTS idx_ivc_inventory ON inventory_vehicle_compat(inventory_id);
CREATE INDEX IF NOT EXISTS idx_ivc_mye ON inventory_vehicle_compat(model_year_engine_id);

-- View to easily query compatibility with vehicle details (join with master DB in app)
CREATE OR REPLACE VIEW v_inventory_vehicle_compat AS
SELECT
    ivc.id,
    ivc.inventory_id,
    ivc.model_year_engine_id,
    ivc.source,
    ivc.confidence,
    ivc.created_at,
    i.part_number,
    i.name as item_name,
    i.brand as item_brand,
    i.price_1,
    i.price_2,
    i.price_3,
    i.image_url
FROM inventory_vehicle_compat ivc
JOIN inventory i ON i.id = ivc.inventory_id;
