-- ─────────────────────────────────────────────────────────────────────────
-- ADDITIVE MIGRATION — creates the ClientUser table (B2B client portal) and
-- wires OperationsSignal.clientId to it. The Prisma schema has defined this
-- model + relation for a while, but no migration ever created the table, so
-- the B2B register/login flow (src/app/actions/clientAuth.ts) and the
-- dashboard client counts were failing at runtime. This backfills it.
--
-- Idempotent: IF NOT EXISTS / duplicate-object guards make it safe to re-run
-- and safe for `migrate deploy` against the existing production DB.
-- ─────────────────────────────────────────────────────────────────────────

CREATE TABLE IF NOT EXISTS "ClientUser" (
    "id" TEXT NOT NULL,
    "email" TEXT NOT NULL,
    "passwordHash" TEXT NOT NULL,
    "fullName" TEXT NOT NULL,
    "companyName" TEXT NOT NULL,
    "phone" TEXT,
    "isApproved" BOOLEAN NOT NULL DEFAULT false,
    "lastLoginAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE UNIQUE INDEX IF NOT EXISTS "ClientUser_email_key" ON "ClientUser" ("email");

-- OperationsSignal.clientId — the FK column the schema references. Add it if
-- a prior schema state never created it (nullable, so existing rows are fine).
ALTER TABLE "OperationsSignal" ADD COLUMN IF NOT EXISTS "clientId" TEXT;

-- Foreign key OperationsSignal.clientId -> ClientUser.id
DO $$ BEGIN
  ALTER TABLE "OperationsSignal"
    ADD CONSTRAINT "OperationsSignal_clientId_fkey"
    FOREIGN KEY ("clientId") REFERENCES "ClientUser"("id")
    ON DELETE SET NULL ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
