-- 009_provider_webhook_tables.sql

-- GitLab webhooks table
CREATE TABLE IF NOT EXISTS gitlab_webhooks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  delivery_id TEXT,
  event_type TEXT NOT NULL,
  action TEXT,
  owner_name TEXT NOT NULL,
  repository_name TEXT NOT NULL,
  repository_id UUID REFERENCES all_repositories(id),
  ref TEXT,
  before_sha TEXT,
  after_sha TEXT,
  commit_count INTEGER DEFAULT 0,
  payload JSONB,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

-- Bitbucket webhooks table
CREATE TABLE IF NOT EXISTS bitbucket_webhooks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  delivery_id TEXT,
  event_type TEXT NOT NULL,
  action TEXT,
  owner_name TEXT NOT NULL,
  repository_name TEXT NOT NULL,
  repository_id UUID REFERENCES all_repositories(id),
  ref TEXT,
  before_sha TEXT,
  after_sha TEXT,
  commit_count INTEGER DEFAULT 0,
  payload JSONB,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

-- Gitea webhooks table
CREATE TABLE IF NOT EXISTS gitea_webhooks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  delivery_id TEXT,
  event_type TEXT NOT NULL,
  action TEXT,
  owner_name TEXT NOT NULL,
  repository_name TEXT NOT NULL,
  repository_id UUID REFERENCES all_repositories(id),
  ref TEXT,
  before_sha TEXT,
  after_sha TEXT,
  commit_count INTEGER DEFAULT 0,
  payload JSONB,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

-- Indexes for better performance
CREATE INDEX IF NOT EXISTS idx_gitlab_webhooks_repository_id ON gitlab_webhooks(repository_id);
CREATE INDEX IF NOT EXISTS idx_gitlab_webhooks_created_at ON gitlab_webhooks(created_at);
CREATE INDEX IF NOT EXISTS idx_gitlab_webhooks_event_type ON gitlab_webhooks(event_type);

CREATE INDEX IF NOT EXISTS idx_bitbucket_webhooks_repository_id ON bitbucket_webhooks(repository_id);
CREATE INDEX IF NOT EXISTS idx_bitbucket_webhooks_created_at ON bitbucket_webhooks(created_at);
CREATE INDEX IF NOT EXISTS idx_bitbucket_webhooks_event_type ON bitbucket_webhooks(event_type);

CREATE INDEX IF NOT EXISTS idx_gitea_webhooks_repository_id ON gitea_webhooks(repository_id);
CREATE INDEX IF NOT EXISTS idx_gitea_webhooks_created_at ON gitea_webhooks(created_at);
CREATE INDEX IF NOT EXISTS idx_gitea_webhooks_event_type ON gitea_webhooks(event_type);
