-- name: CreateRepoAccount :one
INSERT INTO repo_accounts (
    tenant_id,
    provider,
    account_id,
    username,
    encrypted_access_token,
    encrypted_refresh_token
) VALUES (
    $1, $2, $3, $4, $5, $6
) RETURNING *;

-- name: GetRepoAccount :one
SELECT * FROM repo_accounts
WHERE tenant_id = $1 AND provider = $2 AND account_id = $3;

-- name: GetRepoAccountByID :one
SELECT * FROM repo_accounts
WHERE tenant_id = $1 AND id = $2;

-- name: UpdateRepoAccountTokens :one
UPDATE repo_accounts
SET
    encrypted_access_token = $3,
    encrypted_refresh_token = $4,
    updated_at = NOW()
WHERE tenant_id = $1 AND id = $2
RETURNING *;

-- name: ListRepoAccountsByTenant :many
SELECT * FROM repo_accounts
WHERE tenant_id = $1;

-- name: CreateRepository :one
INSERT INTO repositories (
    tenant_id,
    repo_account_id,
    external_id,
    name,
    url
) VALUES (
    $1, $2, $3, $4, $5
) RETURNING *;

-- name: GetRepository :one
SELECT * FROM repositories
WHERE tenant_id = $1 AND id = $2;

-- name: GetRepositoryByExternalID :one
SELECT * FROM repositories
WHERE tenant_id = $1 AND external_id = $2;

-- name: ListRepositoriesByTenant :many
SELECT * FROM repositories
WHERE tenant_id = $1 AND is_active = TRUE;

-- name: CreateWebhook :one
INSERT INTO webhooks (
    tenant_id,
    repository_id,
    external_id,
    secret
) VALUES (
    $1, $2, $3, $4
) RETURNING *;

-- name: GetWebhookByRepoID :one
SELECT * FROM webhooks
WHERE tenant_id = $1 AND repository_id = $2;

-- name: GetWebhookByRepoExternalID :one
SELECT w.* FROM webhooks w
JOIN repositories r ON w.repository_id = r.id
WHERE r.tenant_id = $1 AND r.external_id = $2;

-- name: CreateRepoEvent :one
INSERT INTO repo_events (
    tenant_id,
    repository_id,
    event_type,
    payload
) VALUES (
    $1, $2, $3, $4
) RETURNING *;

