import "server-only";

import { prisma } from "@/lib/db";
import { getSessionUser } from "@/lib/auth/session";

/** Worker / 自動化暫時切換帳號時使用，不走使用者 session。 */
let workerActiveAccountId: string | null = null;

export function setWorkerActiveAccountId(accountId: string | null) {
  workerActiveAccountId = accountId;
}

async function resolveActiveAccountForUser(userId: string) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { activeAccountId: true },
  });
  if (!user) return null;

  if (user.activeAccountId) {
    const account = await prisma.account.findFirst({
      where: { id: user.activeAccountId, userId },
    });
    if (account) return account;
  }

  const account = await prisma.account.findFirst({
    where: { userId },
    orderBy: { updatedAt: "desc" },
  });
  if (account) {
    await prisma.user.update({
      where: { id: userId },
      data: { activeAccountId: account.id },
    });
  }
  return account;
}

export async function getActiveAccountProfile() {
  if (workerActiveAccountId) {
    return prisma.account.findUnique({ where: { id: workerActiveAccountId } });
  }

  const user = await getSessionUser();
  if (!user) return null;
  return resolveActiveAccountForUser(user.id);
}

export async function getActiveAccountId() {
  const account = await getActiveAccountProfile();
  return account?.id ?? null;
}

export async function setActiveAccountForUser(userId: string, accountId: string) {
  await prisma.user.update({
    where: { id: userId },
    data: { activeAccountId: accountId },
  });
}