-- V000: Migration Tracking Table
-- Created: 2025-10-06
-- Purpose: Track which migrations have been applied to the database
-- This should always be the first migration run on a fresh database

-- Create migration tracking table
CREATE TABLE IF NOT EXISTS schema_migrations (
    version VARCHAR(10) PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    checksum VARCHAR(64),
    description TEXT,
    execution_time_ms INTEGER,
    applied_by VARCHAR(100) DEFAULT CURRENT_USER
);

-- Index for quick lookup
CREATE INDEX IF NOT EXISTS idx_schema_migrations_applied_at ON schema_migrations(applied_at);

-- Add comment to table
COMMENT ON TABLE schema_migrations IS 'Tracks database schema migrations that have been applied';
COMMENT ON COLUMN schema_migrations.version IS 'Version number of the migration (e.g., V001, V002)';
COMMENT ON COLUMN schema_migrations.filename IS 'Original filename of the migration script';
COMMENT ON COLUMN schema_migrations.applied_at IS 'Timestamp when the migration was applied';
COMMENT ON COLUMN schema_migrations.checksum IS 'MD5 checksum of the migration file for integrity checking';
COMMENT ON COLUMN schema_migrations.description IS 'Description of what the migration does';
COMMENT ON COLUMN schema_migrations.execution_time_ms IS 'How long the migration took to execute in milliseconds';
COMMENT ON COLUMN schema_migrations.applied_by IS 'Database user who applied the migration';

-- Insert record for this migration
INSERT INTO schema_migrations (version, filename, description)
VALUES ('V000', 'V000_create_migration_tracking.sql', 'Create migration tracking table')
ON CONFLICT (version) DO NOTHING;