-- Create ID sequences table for tracking next ID values
CREATE TABLE IF NOT EXISTS id_sequences (
    entity_type VARCHAR(32) PRIMARY KEY,
    next_value BIGINT NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Initialize sequences from existing data (MAX(id) + 1)
INSERT IGNORE INTO id_sequences (entity_type, next_value)
SELECT 'customer', COALESCE(MAX(id), 0) + 1 FROM customers
UNION ALL
SELECT 'project', COALESCE(MAX(id), 0) + 1 FROM projects
UNION ALL
SELECT 'location', COALESCE(MAX(id), 0) + 1 FROM locations
UNION ALL
SELECT 'lot', COALESCE(MAX(id), 0) + 1 FROM lots
UNION ALL
SELECT 'machine', 1
UNION ALL
SELECT 'part', 1
UNION ALL
SELECT 'installation', COALESCE(MAX(id), 0) + 1 FROM installations
UNION ALL
SELECT 'log_bundle', COALESCE(MAX(id), 0) + 1 FROM log_bundles
UNION ALL
SELECT 'observation', COALESCE(MAX(id), 0) + 1 FROM observations
UNION ALL
SELECT 'timeline_event', COALESCE(MAX(id), 0) + 1 FROM timeline_events
UNION ALL
SELECT 'ticket', COALESCE(MAX(id), 0) + 1 FROM tickets
UNION ALL
SELECT 'ticket_link', COALESCE(MAX(id), 0) + 1 FROM ticket_links
UNION ALL
SELECT 'failure_event', COALESCE(MAX(id), 0) + 1 FROM failure_events;
