-- Migration 005: GitHub webhook tracking and commit SHA history

-- Create a durable table for raw webhook deliveries (compat with existing code expectations)
CREATE TABLE IF NOT EXISTS github_webhooks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  delivery_id VARCHAR(120),
  event_type VARCHAR(100) NOT NULL,
  action VARCHAR(100),
  owner_name VARCHAR(120),
  repository_name VARCHAR(200),
  repository_id UUID REFERENCES github_repositories(id) ON DELETE SET NULL,
  ref VARCHAR(255),
  before_sha VARCHAR(64),
  after_sha VARCHAR(64),
  commit_count INTEGER,
  payload JSONB NOT NULL,
  processed_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_github_webhooks_delivery_id ON github_webhooks(delivery_id);
CREATE INDEX IF NOT EXISTS idx_github_webhooks_repo ON github_webhooks(owner_name, repository_name);
CREATE INDEX IF NOT EXISTS idx_github_webhooks_event_type ON github_webhooks(event_type);

-- Track commit SHA transitions per repository to detect changes over time
CREATE TABLE IF NOT EXISTS repository_commit_events (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  repository_id UUID REFERENCES github_repositories(id) ON DELETE CASCADE,
  ref VARCHAR(255),
  before_sha VARCHAR(64),
  after_sha VARCHAR(64),
  commit_count INTEGER DEFAULT 0,
  received_at TIMESTAMP DEFAULT NOW(),
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_repo_commit_events_repo ON repository_commit_events(repository_id);
CREATE INDEX IF NOT EXISTS idx_repo_commit_events_sha ON repository_commit_events(after_sha);

-- Safe trigger creation
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_trigger WHERE tgname = 'update_github_webhooks_updated_at'
  ) THEN
    CREATE TRIGGER update_github_webhooks_updated_at BEFORE UPDATE ON github_webhooks
      FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
  END IF;
END $$;


