-- [TEC-3065] Add zalo_account_links table for Zalo OA OAuth account linking.
-- Stores per-user OA access/refresh tokens (AES-256-GCM encrypted at app layer)
-- and the last interaction timestamp used for the 24-hour ZNS window check.

CREATE TABLE "zalo_account_links" (
    "id"             TEXT         NOT NULL,
    "userId"         TEXT         NOT NULL,
    "zaloUserId"     TEXT         NOT NULL,
    "accessToken"    TEXT         NOT NULL,
    "refreshToken"   TEXT         NOT NULL,
    "expiresAt"      TIMESTAMP(3) NOT NULL,
    "lastInteractAt" TIMESTAMP(3),
    "createdAt"      TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt"      TIMESTAMP(3) NOT NULL,

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

-- One link per platform user
CREATE UNIQUE INDEX "zalo_account_links_userId_key"   ON "zalo_account_links"("userId");
-- One link per Zalo OA UID
CREATE UNIQUE INDEX "zalo_account_links_zaloUserId_key" ON "zalo_account_links"("zaloUserId");

CREATE INDEX "zalo_account_links_zaloUserId_idx" ON "zalo_account_links"("zaloUserId");
CREATE INDEX "zalo_account_links_expiresAt_idx"  ON "zalo_account_links"("expiresAt");

ALTER TABLE "zalo_account_links"
    ADD CONSTRAINT "zalo_account_links_userId_fkey"
    FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
