-- Create document_locks table for preventing concurrent edits
CREATE TABLE IF NOT EXISTS document_locks (
  id TEXT PRIMARY KEY,
  document_type TEXT NOT NULL,
  document_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  user_name TEXT NOT NULL,
  locked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '30 minutes'),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE(document_type, document_id)
);

-- Create index for efficient queries
CREATE INDEX IF NOT EXISTS idx_document_locks_expires_at ON document_locks(expires_at);
CREATE INDEX IF NOT EXISTS idx_document_locks_user_id ON document_locks(user_id);
CREATE INDEX IF NOT EXISTS idx_document_locks_document_type_id ON document_locks(document_type, document_id);
