import prisma from "./prisma";

export async function getUserByGscsid(gscsid: string) {
  return prisma.user.findUnique({
    where: { gscsid },
    select: {
      id: true,
      gscsid: true,
      firstName: true,
      lastName: true,
      displayName: true,
      email: true,
      timezone: true,
      locale: true,
      createdAt: true,
    },
  });
}

interface EnsureUserData {
  email?: string | null;
  firstName?: string | null;
  lastName?: string | null;
}

/**
 * Get existing user by gscsid, or create a minimal record on first login.
 * Returns the user with id and optional customerId (from metadata).
 */
export async function ensureUser(gscsid: string, data: EnsureUserData) {
  let user = await prisma.user.findUnique({
    where: { gscsid },
    select: {
      id: true,
      gscsid: true,
      email: true,
      firstName: true,
      lastName: true,
      displayName: true,
      metadata: true,
      createdAt: true,
    },
  });

  if (!user) {
    user = await prisma.user.create({
      data: {
        gscsid,
        email: data.email,
        firstName: data.firstName,
        lastName: data.lastName,
        displayName: [data.firstName, data.lastName].filter(Boolean).join(" ") || gscsid,
      },
      select: {
        id: true,
        gscsid: true,
        email: true,
        firstName: true,
        lastName: true,
        displayName: true,
        metadata: true,
        createdAt: true,
      },
    });
  }

  // Extract customerId from metadata if present
  const meta = user.metadata as Record<string, unknown> | null;
  const customerId = (meta?.customerId || meta?.customer_id) as string | undefined;

  return { ...user, customerId };
}
