-- Test Data Database Schema
-- SQLite database for storing and searching test records

-- Main test records table
CREATE TABLE IF NOT EXISTS test_records (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    log_type TEXT NOT NULL,           -- DSCLOG, 5BLOG, 7BLOG, 8BLOG, PWRLOG, SCTLOG, VASLOG, SHT
    model_number TEXT NOT NULL,       -- DSCA38-1793, SCM5B30-01, etc.
    serial_number TEXT NOT NULL,      -- 176923-1, 105840-2, etc.
    test_date TEXT NOT NULL,          -- Test date (YYYY-MM-DD format)
    test_station TEXT,                -- TS-1L, TS-3R, etc.
    overall_result TEXT,              -- PASS/FAIL
    raw_data TEXT,                    -- Full original record
    source_file TEXT,                 -- Original file path
    import_date TEXT DEFAULT (datetime('now')),
    UNIQUE(log_type, model_number, serial_number, test_date, test_station)
);

-- Indexes for fast searching
CREATE INDEX IF NOT EXISTS idx_serial ON test_records(serial_number);
CREATE INDEX IF NOT EXISTS idx_model ON test_records(model_number);
CREATE INDEX IF NOT EXISTS idx_date ON test_records(test_date);
CREATE INDEX IF NOT EXISTS idx_model_serial ON test_records(model_number, serial_number);
CREATE INDEX IF NOT EXISTS idx_result ON test_records(overall_result);
CREATE INDEX IF NOT EXISTS idx_log_type ON test_records(log_type);

-- Full-text search virtual table
CREATE VIRTUAL TABLE IF NOT EXISTS test_records_fts USING fts5(
    serial_number,
    model_number,
    raw_data,
    content='test_records',
    content_rowid='id'
);

-- Triggers to keep FTS index in sync
CREATE TRIGGER IF NOT EXISTS test_records_ai AFTER INSERT ON test_records BEGIN
    INSERT INTO test_records_fts(rowid, serial_number, model_number, raw_data)
    VALUES (new.id, new.serial_number, new.model_number, new.raw_data);
END;

CREATE TRIGGER IF NOT EXISTS test_records_ad AFTER DELETE ON test_records BEGIN
    INSERT INTO test_records_fts(test_records_fts, rowid, serial_number, model_number, raw_data)
    VALUES ('delete', old.id, old.serial_number, old.model_number, old.raw_data);
END;

CREATE TRIGGER IF NOT EXISTS test_records_au AFTER UPDATE ON test_records BEGIN
    INSERT INTO test_records_fts(test_records_fts, rowid, serial_number, model_number, raw_data)
    VALUES ('delete', old.id, old.serial_number, old.model_number, old.raw_data);
    INSERT INTO test_records_fts(rowid, serial_number, model_number, raw_data)
    VALUES (new.id, new.serial_number, new.model_number, new.raw_data);
END;

