-- 075_create_webhooks.sql
-- Webhooks and webhook delivery failure tracking (BE-SEC-012)

-- === WEBHOOKS ===
CREATE TABLE IF NOT EXISTS public.webhooks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,

    url TEXT NOT NULL,
    events TEXT[] NOT NULL DEFAULT '{}',

    active BOOLEAN NOT NULL DEFAULT true,
    secret TEXT NOT NULL DEFAULT '',
    api_key VARCHAR(64) NOT NULL,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_webhooks_api_key ON public.webhooks(api_key) WHERE api_key != '';
CREATE INDEX IF NOT EXISTS idx_webhooks_user_id ON public.webhooks(user_id);
CREATE INDEX IF NOT EXISTS idx_webhooks_active ON public.webhooks(active) WHERE active = true;

COMMENT ON TABLE public.webhooks IS 'Developer webhooks for receiving event notifications';
COMMENT ON COLUMN public.webhooks.api_key IS 'API key for webhook authentication (BE-SEC-012)';

-- === WEBHOOK FAILURES ===
CREATE TABLE IF NOT EXISTS public.webhook_failures (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    webhook_id UUID NOT NULL REFERENCES public.webhooks(id) ON DELETE CASCADE,

    event VARCHAR(255) NOT NULL,
    error TEXT NOT NULL,
    retries INT NOT NULL DEFAULT 0,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_webhook_failures_webhook_id ON public.webhook_failures(webhook_id);
CREATE INDEX IF NOT EXISTS idx_webhook_failures_created_at ON public.webhook_failures(created_at DESC);

COMMENT ON TABLE public.webhook_failures IS 'Webhook delivery failure log for retry and debugging';
