-- Fase 6: enlaces publicos de comprobantes. Posterior a 20260809120000_fase5_notas_credito, no la
-- modifica. Puramente aditiva: una tabla nueva, sin tocar columnas existentes.

CREATE TYPE "EstadoEnlacePublico" AS ENUM ('ACTIVO', 'REVOCADO');

CREATE TABLE "enlaces_publicos" (
    "id" TEXT NOT NULL,
    "comprobanteId" TEXT NOT NULL,
    "tokenHash" TEXT NOT NULL,
    "estado" "EstadoEnlacePublico" NOT NULL DEFAULT 'ACTIVO',
    "expiraEn" TIMESTAMP(3),
    "usuarioCreadorId" TEXT NOT NULL,
    "contadorAccesos" INTEGER NOT NULL DEFAULT 0,
    "ultimoAccesoEn" TIMESTAMP(3),
    "revocadoEn" TIMESTAMP(3),
    "renovadoEn" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "enlaces_publicos_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "enlaces_publicos_tokenHash_key" ON "enlaces_publicos"("tokenHash");
CREATE INDEX "enlaces_publicos_comprobanteId_idx" ON "enlaces_publicos"("comprobanteId");
CREATE INDEX "enlaces_publicos_estado_idx" ON "enlaces_publicos"("estado");
CREATE INDEX "enlaces_publicos_expiraEn_idx" ON "enlaces_publicos"("expiraEn");

ALTER TABLE "enlaces_publicos" ADD CONSTRAINT "enlaces_publicos_comprobanteId_fkey" FOREIGN KEY ("comprobanteId") REFERENCES "comprobantes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "enlaces_publicos" ADD CONSTRAINT "enlaces_publicos_usuarioCreadorId_fkey" FOREIGN KEY ("usuarioCreadorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
