-- v3.2 QWEN Vehicle Compatibility — store unmatched AI vehicles as text
-- Allows saving QWEN fitment results even when the vehicle is not in TecDoc.

-- 1. Allow NULL model_year_engine_id for QWEN vehicles not in master DB
ALTER TABLE inventory_vehicle_compat
    ALTER COLUMN model_year_engine_id DROP NOT NULL;

-- 2. Add text columns for QWEN vehicle details
ALTER TABLE inventory_vehicle_compat
    ADD COLUMN IF NOT EXISTS make VARCHAR(100),
    ADD COLUMN IF NOT EXISTS model VARCHAR(100),
    ADD COLUMN IF NOT EXISTS year INTEGER,
    ADD COLUMN IF NOT EXISTS engine VARCHAR(100),
    ADD COLUMN IF NOT EXISTS engine_code VARCHAR(50);

-- 3. Drop old unique constraint and recreate to handle NULL mye_id
-- (PostgreSQL allows multiple NULLs in a UNIQUE constraint)
ALTER TABLE inventory_vehicle_compat
    DROP CONSTRAINT IF EXISTS inventory_vehicle_compat_inventory_id_model_year_engine_id_key;

ALTER TABLE inventory_vehicle_compat
    ADD CONSTRAINT inventory_vehicle_compat_unique_match
    UNIQUE (inventory_id, model_year_engine_id, make, model, year);

-- 4. Index for fast filtering by inventory + text vehicles
CREATE INDEX IF NOT EXISTS idx_ivc_text_vehicle
    ON inventory_vehicle_compat(inventory_id, make, model, year)
    WHERE model_year_engine_id IS NULL;

-- 5. Update view to include new columns
DROP VIEW IF EXISTS v_inventory_vehicle_compat;
CREATE VIEW v_inventory_vehicle_compat AS
SELECT
    ivc.id,
    ivc.inventory_id,
    ivc.model_year_engine_id,
    ivc.make,
    ivc.model,
    ivc.year,
    ivc.engine,
    ivc.engine_code,
    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;
