-- +migrate Up
CREATE TYPE git_provider AS ENUM ('github', 'gitlab', 'bitbucket');
CREATE TYPE event_type AS ENUM ('push', 'pull_request', 'release');

CREATE TABLE repo_accounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    provider git_provider NOT NULL,
    account_id VARCHAR(255) NOT NULL,
    username VARCHAR(255) NOT NULL,
    encrypted_access_token BYTEA NOT NULL,
    encrypted_refresh_token BYTEA,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(tenant_id, provider, account_id)
);

CREATE TABLE repositories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    repo_account_id UUID NOT NULL REFERENCES repo_accounts(id) ON DELETE CASCADE,
    external_id VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    url VARCHAR(255) NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(tenant_id, external_id)
);

CREATE TABLE webhooks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    repository_id UUID NOT NULL REFERENCES repositories(id) ON DELETE CASCADE,
    external_id VARCHAR(255) NOT NULL,
    secret TEXT NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(tenant_id, repository_id)
);

CREATE TABLE repo_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    repository_id UUID NOT NULL REFERENCES repositories(id),
    event_type event_type NOT NULL,
    payload JSONB NOT NULL,
    processed_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX ON repo_accounts (tenant_id);
CREATE INDEX ON repositories (tenant_id, repo_account_id);
CREATE INDEX ON webhooks (tenant_id, repository_id);
CREATE INDEX ON repo_events (tenant_id, repository_id, event_type);


-- +migrate Down
DROP TABLE IF EXISTS repo_events;
DROP TABLE IF EXISTS webhooks;
DROP TABLE IF EXISTS repositories;
DROP TABLE IF EXISTS repo_accounts;
DROP TYPE IF EXISTS event_type;
DROP TYPE IF EXISTS git_provider;
