import type { Account } from "@prisma/client";
import { prisma } from "@/lib/db";
import { accountHasThreadsToken } from "@/lib/threads-api";
import { AuthError } from "./session";

export async function getUserAccounts(userId: string) {
  return prisma.account.findMany({
    where: { userId },
    orderBy: { updatedAt: "desc" },
  });
}

export async function userHasBoundThreadsAccount(userId: string) {
  const count = await prisma.account.count({
    where: { userId, threadsUserId: { not: null } },
  });
  return count > 0;
}

export async function assertAccountOwnedByUser(userId: string, accountId: string) {
  const account = await prisma.account.findFirst({
    where: { id: accountId, userId },
  });
  if (!account) {
    throw new AuthError("找不到此帳號或無權限存取", 403);
  }
  return account;
}

export function activeAccountHasThreadsAuth(account: Account | null) {
  return accountHasThreadsToken(account);
}