import { prisma } from "./prisma.js";

export type ClientSponsorSummary = {
  id: string;
  entityType: "person" | "company";
  name: string;
  firstName: string | null;
  lastName: string | null;
  companyName: string | null;
  email: string | null;
  phone: string | null;
};

type SponsorRow = {
  id: string;
  client_id: string;
  entity_type: string;
  first_name: string | null;
  last_name: string | null;
  company_name: string | null;
  preferred_name: string | null;
  email: string | null;
  phone: string | null;
};

function normalizeEntityType(value: string | null | undefined): "person" | "company" {
  return value === "company" ? "company" : "person";
}

export function formatSponsorName(row: {
  entity_type?: string | null;
  first_name?: string | null;
  last_name?: string | null;
  company_name?: string | null;
  preferred_name?: string | null;
}) {
  const preferredName = row.preferred_name?.trim();
  const fullName = [row.first_name?.trim(), row.last_name?.trim()].filter(Boolean).join(" ").trim();
  const companyName = row.company_name?.trim();

  if (normalizeEntityType(row.entity_type) === "company") {
    return companyName || preferredName || fullName || "Unnamed sponsor";
  }

  return preferredName || fullName || companyName || "Unnamed sponsor";
}

export function serializeClientSponsor(row: SponsorRow): ClientSponsorSummary {
  return {
    id: row.id,
    entityType: normalizeEntityType(row.entity_type),
    name: formatSponsorName(row),
    firstName: row.first_name,
    lastName: row.last_name,
    companyName: row.company_name,
    email: row.email,
    phone: row.phone,
  };
}

export async function listClientSponsorsByClientIds(input: {
  lawFirmId: string;
  clientIds: string[];
}) {
  if (input.clientIds.length === 0) {
    return new Map<string, ClientSponsorSummary>();
  }

  const rows = await prisma.relatedParty.findMany({
    where: {
      law_firm_id: input.lawFirmId,
      client_id: {
        in: input.clientIds,
      },
      relation_type: "sponsor",
      deleted_at: null,
    },
    orderBy: [{ updated_at: "desc" }, { created_at: "desc" }],
  });

  const sponsorMap = new Map<string, ClientSponsorSummary>();

  for (const row of rows) {
    if (sponsorMap.has(row.client_id)) {
      continue;
    }

    sponsorMap.set(
      row.client_id,
      serializeClientSponsor({
        id: row.id,
        client_id: row.client_id,
        entity_type: row.entity_type,
        first_name: row.first_name,
        last_name: row.last_name,
        company_name: row.company_name,
        preferred_name: row.preferred_name,
        email: row.email,
        phone: row.phone,
      }),
    );
  }

  return sponsorMap;
}
