-- ============================================================================
-- EJEMPLO COMPLETO DE BASE DE DATOS DE AUTOPARTES
-- Muestra cómo quedará la base de datos al completar todas las fases
-- ============================================================================

-- ============================================================================
-- TABLAS EXISTENTES (Ya implementadas)
-- ============================================================================

-- Marcas de vehículos
INSERT INTO brands (id, name, country, founded_year) VALUES
(1, 'Toyota', 'Japan', 1937),
(2, 'Honda', 'Japan', 1948),
(3, 'Ford', 'USA', 1903),
(4, 'Chevrolet', 'USA', 1911),
(5, 'Volkswagen', 'Germany', 1937);

-- Años
INSERT INTO years (id, year) VALUES
(1, 2020), (2, 2021), (3, 2022), (4, 2023), (5, 2024);

-- Motores
INSERT INTO engines (id, name, displacement_cc, cylinders, fuel_type, power_hp, torque_nm, engine_code) VALUES
(1, '2.5L 4-Cyl Dynamic Force', 2487, 4, 'gasoline', 203, 250, 'A25A-FKS'),
(2, '2.5L Hybrid', 2487, 4, 'hybrid', 215, 221, 'A25A-FXS'),
(3, '3.5L V6', 3456, 6, 'gasoline', 301, 362, '2GR-FKS'),
(4, '1.5L Turbo', 1498, 4, 'gasoline', 192, 260, 'L15CA'),
(5, '2.0L Turbo EcoBoost', 1999, 4, 'gasoline', 250, 373, 'EcoBoost');

-- Modelos
INSERT INTO models (id, brand_id, name, body_type, generation, production_start_year, production_end_year) VALUES
(1, 1, 'Camry', 'sedan', 'XV70', 2018, NULL),
(2, 1, 'Corolla', 'sedan', 'E210', 2019, NULL),
(3, 1, 'RAV4', 'suv', 'XA50', 2019, NULL),
(4, 2, 'Civic', 'sedan', '11th Gen', 2022, NULL),
(5, 2, 'CR-V', 'suv', '6th Gen', 2023, NULL),
(6, 3, 'F-150', 'truck', '14th Gen', 2021, NULL);

-- Configuraciones Modelo-Año-Motor (model_year_engine)
INSERT INTO model_year_engine (id, model_id, year_id, engine_id, trim_level, drivetrain, transmission) VALUES
-- Toyota Camry 2023
(1, 1, 4, 1, 'LE', 'FWD', 'automatic'),
(2, 1, 4, 1, 'SE', 'FWD', 'automatic'),
(3, 1, 4, 1, 'XLE', 'AWD', 'automatic'),
(4, 1, 4, 2, 'SE Hybrid', 'FWD', 'CVT'),
(5, 1, 4, 3, 'XSE V6', 'FWD', 'automatic'),
-- Toyota Camry 2024
(6, 1, 5, 1, 'LE', 'FWD', 'automatic'),
(7, 1, 5, 2, 'SE Hybrid', 'FWD', 'CVT'),
-- Honda Civic 2023
(8, 4, 4, 4, 'Sport', 'FWD', 'CVT'),
(9, 4, 4, 4, 'Touring', 'FWD', 'CVT');

-- ============================================================================
-- FASE 1: CATÁLOGO DE PARTES (Implementado)
-- ============================================================================

-- Categorías principales
INSERT INTO part_categories (id, name, name_es, slug, icon_name, display_order) VALUES
(1, 'Body & Lamp Assembly', 'Carrocería y Lámparas', 'body-lamp', 'fa-car-side', 1),
(2, 'Brake & Wheel Hub', 'Frenos y Mazas', 'brake-wheel', 'fa-compact-disc', 2),
(3, 'Cooling System', 'Sistema de Enfriamiento', 'cooling', 'fa-temperature-low', 3),
(4, 'Drivetrain', 'Tren Motriz', 'drivetrain', 'fa-cogs', 4),
(5, 'Electrical & Lighting', 'Eléctrico e Iluminación', 'electrical', 'fa-bolt', 5),
(6, 'Engine', 'Motor', 'engine', 'fa-cog', 6),
(7, 'Exhaust', 'Escape', 'exhaust', 'fa-wind', 7),
(8, 'Fuel & Air', 'Combustible y Aire', 'fuel-air', 'fa-gas-pump', 8),
(9, 'Heat & Air Conditioning', 'Calefacción y A/C', 'hvac', 'fa-snowflake', 9),
(10, 'Steering', 'Dirección', 'steering', 'fa-dharmachakra', 10),
(11, 'Suspension', 'Suspensión', 'suspension', 'fa-truck-monster', 11),
(12, 'Transmission', 'Transmisión', 'transmission', 'fa-gears', 12);

-- Grupos dentro de categorías (ejemplos)
INSERT INTO part_groups (id, category_id, name, name_es, slug, display_order) VALUES
-- Engine groups
(1, 6, 'Oil Filters', 'Filtros de Aceite', 'oil-filters', 1),
(2, 6, 'Air Filters', 'Filtros de Aire', 'air-filters', 2),
(3, 6, 'Spark Plugs', 'Bujías', 'spark-plugs', 3),
(4, 6, 'Timing Belt & Chain', 'Banda/Cadena de Tiempo', 'timing', 4),
(5, 6, 'Gaskets & Seals', 'Juntas y Sellos', 'gaskets', 5),
(6, 6, 'Engine Mounts', 'Soportes de Motor', 'mounts', 6),
-- Brake groups
(10, 2, 'Brake Pads', 'Balatas/Pastillas', 'brake-pads', 1),
(11, 2, 'Brake Rotors', 'Discos de Freno', 'brake-rotors', 2),
(12, 2, 'Brake Calipers', 'Calipers', 'brake-calipers', 3),
(13, 2, 'Brake Lines', 'Líneas de Freno', 'brake-lines', 4),
(14, 2, 'Wheel Bearings', 'Baleros de Rueda', 'wheel-bearings', 5),
-- Suspension groups
(20, 11, 'Shocks & Struts', 'Amortiguadores', 'shocks-struts', 1),
(21, 11, 'Control Arms', 'Brazos de Control', 'control-arms', 2),
(22, 11, 'Ball Joints', 'Rótulas', 'ball-joints', 3),
(23, 11, 'Tie Rod Ends', 'Terminales', 'tie-rods', 4),
(24, 11, 'Sway Bar Links', 'Ligas de Barra Estabilizadora', 'sway-bar', 5),
-- Electrical groups
(30, 5, 'Batteries', 'Baterías', 'batteries', 1),
(31, 5, 'Alternators', 'Alternadores', 'alternators', 2),
(32, 5, 'Starters', 'Marchas', 'starters', 3),
(33, 5, 'Ignition Coils', 'Bobinas de Ignición', 'ignition-coils', 4),
(34, 5, 'Sensors', 'Sensores', 'sensors', 5);

-- Partes OEM (catálogo maestro)
INSERT INTO parts (id, oem_part_number, name, name_es, group_id, description, description_es, weight_kg, material) VALUES
-- Filtros de aceite Toyota
(1, '04152-YZZA1', 'Oil Filter Element', 'Elemento Filtro de Aceite', 1,
   'Genuine Toyota oil filter for 2.5L engines', 'Filtro de aceite genuino Toyota para motores 2.5L', 0.3, 'Paper/Metal'),
(2, '04152-YZZA5', 'Oil Filter Element', 'Elemento Filtro de Aceite', 1,
   'Genuine Toyota oil filter for 3.5L V6 engines', 'Filtro de aceite genuino Toyota para motores 3.5L V6', 0.35, 'Paper/Metal'),

-- Filtros de aire
(3, '17801-0V020', 'Air Filter Element', 'Elemento Filtro de Aire', 2,
   'Engine air filter for Camry 2.5L', 'Filtro de aire motor para Camry 2.5L', 0.4, 'Paper'),
(4, '17801-38051', 'Air Filter Element', 'Elemento Filtro de Aire', 2,
   'Engine air filter for Camry V6', 'Filtro de aire motor para Camry V6', 0.45, 'Paper'),

-- Bujías
(5, '90919-01275', 'Spark Plug - Iridium', 'Bujía - Iridio', 3,
   'Denso Iridium TT spark plug', 'Bujía Denso Iridium TT', 0.05, 'Iridium/Nickel'),
(6, '90919-01253', 'Spark Plug - Standard', 'Bujía - Estándar', 3,
   'NGK Standard spark plug', 'Bujía NGK Estándar', 0.05, 'Nickel'),

-- Pastillas de freno
(10, '04465-06200', 'Front Brake Pads', 'Pastillas de Freno Delanteras', 10,
    'Genuine Toyota front brake pad set', 'Juego de pastillas delanteras genuinas Toyota', 1.2, 'Ceramic'),
(11, '04466-06200', 'Rear Brake Pads', 'Pastillas de Freno Traseras', 10,
    'Genuine Toyota rear brake pad set', 'Juego de pastillas traseras genuinas Toyota', 0.9, 'Ceramic'),

-- Discos de freno
(12, '43512-06190', 'Front Brake Rotor', 'Disco de Freno Delantero', 11,
    'Genuine Toyota front brake rotor', 'Disco de freno delantero genuino Toyota', 8.5, 'Cast Iron'),
(13, '42431-06190', 'Rear Brake Rotor', 'Disco de Freno Trasero', 11,
    'Genuine Toyota rear brake rotor', 'Disco de freno trasero genuino Toyota', 5.2, 'Cast Iron'),

-- Amortiguadores
(20, '48510-06780', 'Front Strut Assembly', 'Amortiguador Delantero Completo', 20,
    'Front strut assembly with spring', 'Amortiguador delantero con resorte', 12.5, 'Steel'),
(21, '48530-06400', 'Rear Shock Absorber', 'Amortiguador Trasero', 20,
    'Rear shock absorber', 'Amortiguador trasero', 3.8, 'Steel'),

-- Rótulas y terminales
(22, '43330-09510', 'Lower Ball Joint', 'Rótula Inferior', 22,
    'Front lower ball joint', 'Rótula inferior delantera', 0.8, 'Steel'),
(23, '45046-09631', 'Outer Tie Rod End', 'Terminal Exterior', 23,
    'Steering outer tie rod end', 'Terminal exterior de dirección', 0.5, 'Steel'),

-- Sensores
(30, '89467-06150', 'Oxygen Sensor - Upstream', 'Sensor de Oxígeno - Arriba', 34,
    'Primary oxygen sensor (Bank 1)', 'Sensor de oxígeno primario (Banco 1)', 0.15, 'Ceramic/Metal'),
(31, '89467-06160', 'Oxygen Sensor - Downstream', 'Sensor de Oxígeno - Abajo', 34,
    'Secondary oxygen sensor (Bank 1)', 'Sensor de oxígeno secundario (Banco 1)', 0.15, 'Ceramic/Metal');

-- Fitment: Qué partes van en qué vehículos
INSERT INTO vehicle_parts (id, model_year_engine_id, part_id, quantity_required, position, fitment_notes) VALUES
-- Toyota Camry 2023 2.5L LE (mye_id = 1)
(1, 1, 1, 1, NULL, 'Use with 2.5L 4-Cyl engine only'),
(2, 1, 3, 1, NULL, NULL),
(3, 1, 5, 4, NULL, 'Gap: 0.043 inch'),
(4, 1, 10, 1, 'front', NULL),
(5, 1, 11, 1, 'rear', NULL),
(6, 1, 12, 2, 'front', 'Left and Right'),
(7, 1, 13, 2, 'rear', 'Left and Right'),
(8, 1, 20, 2, 'front', 'Left and Right'),
(9, 1, 21, 2, 'rear', 'Left and Right'),
(10, 1, 22, 2, 'front-lower', 'Left and Right'),
(11, 1, 23, 2, 'front', 'Left and Right'),
(12, 1, 30, 1, 'upstream', 'Bank 1 Sensor 1'),
(13, 1, 31, 1, 'downstream', 'Bank 1 Sensor 2'),

-- Toyota Camry 2023 V6 XSE (mye_id = 5)
(20, 5, 2, 1, NULL, 'Use with 3.5L V6 engine only'),
(21, 5, 4, 1, NULL, NULL),
(22, 5, 6, 6, NULL, 'V6 requires 6 spark plugs'),
(23, 5, 10, 1, 'front', NULL),
(24, 5, 11, 1, 'rear', NULL);

-- ============================================================================
-- FASE 2: CROSS-REFERENCES Y AFTERMARKET (Por implementar)
-- ============================================================================

-- Fabricantes (OEM y aftermarket)
CREATE TABLE IF NOT EXISTS manufacturers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    type TEXT CHECK(type IN ('oem', 'aftermarket', 'remanufactured')),
    quality_tier TEXT CHECK(quality_tier IN ('economy', 'standard', 'premium', 'oem')),
    country TEXT,
    logo_url TEXT,
    website TEXT
);

INSERT INTO manufacturers (id, name, type, quality_tier, country, website) VALUES
(1, 'Toyota', 'oem', 'oem', 'Japan', 'https://parts.toyota.com'),
(2, 'Honda', 'oem', 'oem', 'Japan', 'https://parts.honda.com'),
(3, 'Bosch', 'aftermarket', 'premium', 'Germany', 'https://www.boschparts.com'),
(4, 'Denso', 'aftermarket', 'premium', 'Japan', 'https://www.denso.com'),
(5, 'NGK', 'aftermarket', 'premium', 'Japan', 'https://www.ngk.com'),
(6, 'Akebono', 'aftermarket', 'premium', 'Japan', 'https://www.akebono.com'),
(7, 'Brembo', 'aftermarket', 'premium', 'Italy', 'https://www.brembo.com'),
(8, 'Monroe', 'aftermarket', 'standard', 'USA', 'https://www.monroe.com'),
(9, 'KYB', 'aftermarket', 'premium', 'Japan', 'https://www.kyb.com'),
(10, 'Moog', 'aftermarket', 'premium', 'USA', 'https://www.moogparts.com'),
(11, 'Fram', 'aftermarket', 'economy', 'USA', 'https://www.fram.com'),
(12, 'WIX', 'aftermarket', 'standard', 'USA', 'https://www.wixfilters.com'),
(13, 'K&N', 'aftermarket', 'premium', 'USA', 'https://www.knfilters.com'),
(14, 'Motorcraft', 'oem', 'oem', 'USA', 'https://www.motorcraft.com'),
(15, 'ACDelco', 'oem', 'oem', 'USA', 'https://www.acdelco.com');

-- Partes aftermarket vinculadas a OEM
CREATE TABLE IF NOT EXISTS aftermarket_parts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    oem_part_id INTEGER NOT NULL,
    manufacturer_id INTEGER NOT NULL,
    part_number TEXT NOT NULL,
    name TEXT,
    name_es TEXT,
    quality_tier TEXT CHECK(quality_tier IN ('economy', 'standard', 'premium')),
    price_usd REAL,
    warranty_months INTEGER,
    FOREIGN KEY (oem_part_id) REFERENCES parts(id),
    FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id)
);

INSERT INTO aftermarket_parts (id, oem_part_id, manufacturer_id, part_number, name, name_es, quality_tier, price_usd, warranty_months) VALUES
-- Alternativas para filtro de aceite Toyota 04152-YZZA1
(1, 1, 3, '3311', 'Premium Oil Filter', 'Filtro Aceite Premium', 'premium', 12.99, 12),
(2, 1, 11, 'XG9972', 'Ultra Synthetic Oil Filter', 'Filtro Aceite Sintético', 'standard', 8.49, 12),
(3, 1, 12, '57047', 'Oil Filter', 'Filtro de Aceite', 'standard', 7.99, 6),

-- Alternativas para filtro de aire Toyota 17801-0V020
(4, 3, 13, '33-5057', 'High-Flow Air Filter', 'Filtro Aire Alto Flujo', 'premium', 54.99, 120), -- K&N lifetime
(5, 3, 11, 'CA11476', 'Extra Guard Air Filter', 'Filtro Aire Extra Guard', 'economy', 18.99, 12),
(6, 3, 3, 'F00E164749', 'Workshop Air Filter', 'Filtro Aire Taller', 'premium', 24.99, 24),

-- Alternativas para bujías
(7, 5, 4, 'IK20TT', 'Iridium TT Spark Plug', 'Bujía Iridium TT', 'premium', 11.99, 60),
(8, 5, 5, 'ILKAR7B11', 'Laser Iridium Spark Plug', 'Bujía Laser Iridium', 'premium', 13.99, 60),
(9, 6, 3, 'FR7DC+', 'Super Plus Spark Plug', 'Bujía Super Plus', 'standard', 4.99, 24),

-- Alternativas para pastillas de freno
(10, 10, 6, 'ACT1293', 'ProACT Ultra-Premium Ceramic', 'Cerámica Ultra-Premium', 'premium', 89.99, 36),
(11, 10, 7, 'P83124N', 'Premium NAO Ceramic Pads', 'Pastillas Cerámicas NAO', 'premium', 129.99, 24),
(12, 10, 3, 'BC1293', 'QuietCast Ceramic Pads', 'Pastillas Cerámicas QuietCast', 'standard', 54.99, 24),

-- Alternativas para amortiguadores
(13, 20, 8, '72389', 'OESpectrum Strut Assembly', 'Ensamble Amortiguador OE', 'standard', 189.99, 24),
(14, 20, 9, '339407', 'Excel-G Strut Assembly', 'Ensamble Amortiguador Excel-G', 'premium', 229.99, 36),
(15, 21, 8, '37324', 'OESpectrum Shock', 'Amortiguador OESpectrum', 'standard', 54.99, 24),
(16, 21, 9, '341461', 'Excel-G Shock', 'Amortiguador Excel-G', 'premium', 69.99, 36);

-- Cross-references (números alternativos)
CREATE TABLE IF NOT EXISTS part_cross_references (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    part_id INTEGER NOT NULL,
    cross_reference_number TEXT NOT NULL,
    reference_type TEXT CHECK(reference_type IN ('oem_alternate', 'supersession', 'interchange', 'competitor')),
    source TEXT,
    notes TEXT,
    FOREIGN KEY (part_id) REFERENCES parts(id)
);

INSERT INTO part_cross_references (id, part_id, cross_reference_number, reference_type, source, notes) VALUES
-- Oil filter cross-refs
(1, 1, '04152-YZZA3', 'oem_alternate', 'Toyota', 'Earlier part number'),
(2, 1, '04152-31090', 'oem_alternate', 'Toyota', 'Lexus equivalent'),
(3, 1, 'L14476', 'interchange', 'Purolator', NULL),
(4, 1, 'CH10358', 'interchange', 'Champion', NULL),

-- Spark plug cross-refs
(5, 5, 'SK20R11', 'oem_alternate', 'Denso', 'Denso part number'),
(6, 5, '3297', 'interchange', 'NGK', 'ILKAR7B11 equivalent'),

-- Brake pad cross-refs
(7, 10, '04465-06201', 'supersession', 'Toyota', 'Superseded from'),
(8, 10, '04465-33450', 'oem_alternate', 'Lexus', 'Lexus ES equivalent');

-- ============================================================================
-- FASE 3: DIAGRAMAS EXPLOSIONADOS (Por implementar)
-- ============================================================================

-- Diagramas
CREATE TABLE IF NOT EXISTS diagrams (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    name_es TEXT,
    group_id INTEGER NOT NULL,
    image_path TEXT NOT NULL,
    thumbnail_path TEXT,
    display_order INTEGER DEFAULT 0,
    source TEXT,
    FOREIGN KEY (group_id) REFERENCES part_groups(id)
);

INSERT INTO diagrams (id, name, name_es, group_id, image_path, thumbnail_path, display_order, source) VALUES
(1, 'Front Brake Assembly', 'Ensamble Freno Delantero', 10,
   '/static/diagrams/toyota/camry/2023/front_brake_assembly.svg',
   '/static/diagrams/toyota/camry/2023/front_brake_assembly_thumb.png', 1, 'Toyota TIS'),
(2, 'Rear Brake Assembly', 'Ensamble Freno Trasero', 10,
   '/static/diagrams/toyota/camry/2023/rear_brake_assembly.svg',
   '/static/diagrams/toyota/camry/2023/rear_brake_assembly_thumb.png', 2, 'Toyota TIS'),
(3, 'Front Suspension', 'Suspensión Delantera', 20,
   '/static/diagrams/toyota/camry/2023/front_suspension.svg',
   '/static/diagrams/toyota/camry/2023/front_suspension_thumb.png', 1, 'Toyota TIS'),
(4, 'Engine Oil System', 'Sistema de Aceite Motor', 1,
   '/static/diagrams/toyota/camry/2023/engine_oil_system.svg',
   '/static/diagrams/toyota/camry/2023/engine_oil_system_thumb.png', 1, 'Toyota TIS'),
(5, 'Ignition System', 'Sistema de Ignición', 3,
   '/static/diagrams/toyota/camry/2023/ignition_system.svg',
   '/static/diagrams/toyota/camry/2023/ignition_system_thumb.png', 1, 'Toyota TIS');

-- Diagramas específicos por vehículo
CREATE TABLE IF NOT EXISTS vehicle_diagrams (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    diagram_id INTEGER NOT NULL,
    model_year_engine_id INTEGER NOT NULL,
    notes TEXT,
    FOREIGN KEY (diagram_id) REFERENCES diagrams(id),
    FOREIGN KEY (model_year_engine_id) REFERENCES model_year_engine(id),
    UNIQUE(diagram_id, model_year_engine_id)
);

INSERT INTO vehicle_diagrams (id, diagram_id, model_year_engine_id, notes) VALUES
(1, 1, 1, NULL),  -- Front brake diagram for Camry 2023 2.5L LE
(2, 2, 1, NULL),  -- Rear brake diagram
(3, 3, 1, NULL),  -- Front suspension diagram
(4, 4, 1, 'For 2.5L 4-Cyl engines'),
(5, 5, 1, NULL),
(6, 1, 5, 'V6 uses same brakes'),  -- Same brake for V6
(7, 4, 5, 'For 3.5L V6 engines');

-- Hotspots clickeables en diagramas
CREATE TABLE IF NOT EXISTS diagram_hotspots (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    diagram_id INTEGER NOT NULL,
    part_id INTEGER NOT NULL,
    callout_number INTEGER,
    shape TEXT DEFAULT 'rect' CHECK(shape IN ('rect', 'circle', 'poly')),
    coords TEXT NOT NULL,  -- x1,y1,x2,y2 for rect; cx,cy,r for circle; x1,y1,x2,y2,... for poly
    FOREIGN KEY (diagram_id) REFERENCES diagrams(id),
    FOREIGN KEY (part_id) REFERENCES parts(id)
);

INSERT INTO diagram_hotspots (id, diagram_id, part_id, callout_number, shape, coords) VALUES
-- Front Brake Assembly hotspots
(1, 1, 10, 1, 'rect', '150,200,250,280'),   -- Brake Pads
(2, 1, 12, 2, 'rect', '100,150,300,350'),   -- Brake Rotor
(3, 1, NULL, 3, 'rect', '280,180,380,300'), -- Caliper (not in our parts yet)

-- Front Suspension hotspots
(4, 3, 20, 1, 'rect', '200,50,300,250'),    -- Strut Assembly
(5, 3, 22, 2, 'circle', '250,400,30'),      -- Ball Joint
(6, 3, 23, 3, 'circle', '150,350,25'),      -- Tie Rod End
(7, 3, NULL, 4, 'rect', '100,200,180,380'), -- Control Arm

-- Engine Oil System hotspots
(8, 4, 1, 1, 'rect', '300,250,400,350'),    -- Oil Filter

-- Ignition System hotspots
(9, 5, 5, 1, 'rect', '150,100,200,180'),    -- Spark Plug 1
(10, 5, 5, 2, 'rect', '220,100,270,180'),   -- Spark Plug 2
(11, 5, 5, 3, 'rect', '290,100,340,180'),   -- Spark Plug 3
(12, 5, 5, 4, 'rect', '360,100,410,180');   -- Spark Plug 4

-- ============================================================================
-- FASE 4: BÚSQUEDA FULL-TEXT Y VIN DECODER (Por implementar)
-- ============================================================================

-- Full-Text Search (SQLite FTS5)
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
    oem_part_number,
    name,
    name_es,
    description,
    description_es,
    content='parts',
    content_rowid='id'
);

-- Triggers para sincronización automática
CREATE TRIGGER IF NOT EXISTS parts_ai AFTER INSERT ON parts BEGIN
    INSERT INTO parts_fts(rowid, oem_part_number, name, name_es, description, description_es)
    VALUES (new.id, new.oem_part_number, new.name, new.name_es, new.description, new.description_es);
END;

CREATE TRIGGER IF NOT EXISTS parts_ad AFTER DELETE ON parts BEGIN
    INSERT INTO parts_fts(parts_fts, rowid, oem_part_number, name, name_es, description, description_es)
    VALUES ('delete', old.id, old.oem_part_number, old.name, old.name_es, old.description, old.description_es);
END;

CREATE TRIGGER IF NOT EXISTS parts_au AFTER UPDATE ON parts BEGIN
    INSERT INTO parts_fts(parts_fts, rowid, oem_part_number, name, name_es, description, description_es)
    VALUES ('delete', old.id, old.oem_part_number, old.name, old.name_es, old.description, old.description_es);
    INSERT INTO parts_fts(rowid, oem_part_number, name, name_es, description, description_es)
    VALUES (new.id, new.oem_part_number, new.name, new.name_es, new.description, new.description_es);
END;

-- Cache de VINs decodificados
CREATE TABLE IF NOT EXISTS vin_cache (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    vin TEXT NOT NULL UNIQUE,
    decoded_data TEXT NOT NULL,  -- JSON from NHTSA API
    model_year_engine_id INTEGER,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    expires_at DATETIME,
    FOREIGN KEY (model_year_engine_id) REFERENCES model_year_engine(id)
);

INSERT INTO vin_cache (id, vin, decoded_data, model_year_engine_id, expires_at) VALUES
(1, '4T1BF1FK5CU123456', '{
    "Make": "TOYOTA",
    "Model": "Camry",
    "ModelYear": "2023",
    "BodyClass": "Sedan/Saloon",
    "DriveType": "FWD/Front-Wheel Drive",
    "EngineConfiguration": "In-Line",
    "EngineCylinders": "4",
    "DisplacementL": "2.5",
    "FuelTypePrimary": "Gasoline",
    "TransmissionStyle": "Automatic"
}', 1, '2026-03-05'),

(2, '4T1K61AK5PU234567', '{
    "Make": "TOYOTA",
    "Model": "Camry",
    "ModelYear": "2023",
    "BodyClass": "Sedan/Saloon",
    "DriveType": "FWD/Front-Wheel Drive",
    "EngineConfiguration": "V-Type",
    "EngineCylinders": "6",
    "DisplacementL": "3.5",
    "FuelTypePrimary": "Gasoline",
    "TransmissionStyle": "Automatic"
}', 5, '2026-03-05');

-- ============================================================================
-- FASE 5: OPTIMIZACIÓN - ÍNDICES ADICIONALES
-- ============================================================================

-- Índices compuestos para queries frecuentes
CREATE INDEX IF NOT EXISTS idx_vehicle_parts_mye_part ON vehicle_parts(model_year_engine_id, part_id);
CREATE INDEX IF NOT EXISTS idx_aftermarket_oem ON aftermarket_parts(oem_part_id);
CREATE INDEX IF NOT EXISTS idx_aftermarket_manufacturer ON aftermarket_parts(manufacturer_id);
CREATE INDEX IF NOT EXISTS idx_cross_ref_part ON part_cross_references(part_id);
CREATE INDEX IF NOT EXISTS idx_cross_ref_number ON part_cross_references(cross_reference_number);
CREATE INDEX IF NOT EXISTS idx_diagrams_group ON diagrams(group_id);
CREATE INDEX IF NOT EXISTS idx_hotspots_diagram ON diagram_hotspots(diagram_id);
CREATE INDEX IF NOT EXISTS idx_hotspots_part ON diagram_hotspots(part_id);
CREATE INDEX IF NOT EXISTS idx_vin_cache_vin ON vin_cache(vin);

-- ============================================================================
-- QUERIES DE EJEMPLO
-- ============================================================================

-- 1. Buscar todas las partes para un vehículo específico
/*
SELECT
    pc.name_es AS categoria,
    pg.name_es AS grupo,
    p.oem_part_number,
    p.name_es AS nombre,
    vp.quantity_required AS cantidad,
    vp.position AS posicion
FROM vehicle_parts vp
JOIN parts p ON vp.part_id = p.id
JOIN part_groups pg ON p.group_id = pg.id
JOIN part_categories pc ON pg.category_id = pc.id
WHERE vp.model_year_engine_id = 1
ORDER BY pc.display_order, pg.display_order;
*/

-- 2. Buscar alternativas aftermarket para una parte OEM
/*
SELECT
    m.name AS fabricante,
    m.quality_tier AS calidad,
    ap.part_number,
    ap.name_es AS nombre,
    ap.price_usd AS precio,
    ap.warranty_months AS garantia_meses
FROM aftermarket_parts ap
JOIN manufacturers m ON ap.manufacturer_id = m.id
WHERE ap.oem_part_id = 1
ORDER BY m.quality_tier DESC, ap.price_usd;
*/

-- 3. Búsqueda full-text de partes
/*
SELECT p.*
FROM parts p
JOIN parts_fts ON p.id = parts_fts.rowid
WHERE parts_fts MATCH 'filtro aceite'
ORDER BY rank;
*/

-- 4. Obtener hotspots de un diagrama con info de partes
/*
SELECT
    dh.callout_number,
    dh.shape,
    dh.coords,
    p.oem_part_number,
    p.name_es AS nombre
FROM diagram_hotspots dh
LEFT JOIN parts p ON dh.part_id = p.id
WHERE dh.diagram_id = 1
ORDER BY dh.callout_number;
*/

-- 5. Buscar por número de parte (incluye cross-references)
/*
SELECT DISTINCT
    p.id,
    p.oem_part_number,
    p.name_es,
    'OEM' AS source
FROM parts p
WHERE p.oem_part_number LIKE '%04152%'

UNION

SELECT DISTINCT
    p.id,
    p.oem_part_number,
    p.name_es,
    'Cross-Ref: ' || pcr.cross_reference_number AS source
FROM parts p
JOIN part_cross_references pcr ON p.id = pcr.part_id
WHERE pcr.cross_reference_number LIKE '%04152%';
*/
