import type { Contact } from "@/lib/api/types.gen";
import type { StudyContactRow, StudySeasonRow } from "../types";

export function mapContactsFromApi(contacts?: Contact[]): StudyContactRow[] {
  return (contacts ?? [])
    .filter((contact) => Boolean(contact.contactDbId))
    .map((contact) => ({
      ...contact,
      contactDbId: contact.contactDbId as string,
      name: contact.name ?? contact.contactDbId,
    }));
}

export function mapSeasonsFromApi(seasonDbIds?: string[]): StudySeasonRow[] {
  return (seasonDbIds ?? [])
    .filter((seasonDbId) => Boolean(String(seasonDbId).trim()))
    .map((seasonDbId) => ({
      seasonDbId: String(seasonDbId),
      label: String(seasonDbId),
    }));
}

export function normalizeContactsForSave(contacts: StudyContactRow[]): Contact[] {
  const seen = new Set<string>();
  const normalized: Contact[] = [];

  for (const contact of contacts) {
    const contactDbId = String(contact.contactDbId ?? "").trim();
    if (!contactDbId) continue;
    if (seen.has(contactDbId)) {
      throw new Error("同一研究不能重复添加相同联系人");
    }
    seen.add(contactDbId);
    normalized.push({ contactDbId, name: contact.name });
  }

  return normalized;
}

export function normalizeSeasonsForSave(seasons: StudySeasonRow[]): string[] {
  const seen = new Set<string>();
  const normalized: string[] = [];

  for (const season of seasons) {
    const seasonDbId = String(season.seasonDbId ?? "").trim();
    if (!seasonDbId) continue;
    if (seen.has(seasonDbId)) {
      throw new Error("同一研究不能重复绑定相同季节");
    }
    seen.add(seasonDbId);
    normalized.push(seasonDbId);
  }

  return normalized;
}

export function readStudyContacts(payload: Record<string, unknown>): StudyContactRow[] {
  const value = payload.studyContacts;
  if (Array.isArray(value)) return value as StudyContactRow[];
  return mapContactsFromApi(payload.contacts as Contact[] | undefined);
}

export function readStudySeasons(payload: Record<string, unknown>): StudySeasonRow[] {
  const value = payload.studySeasons;
  if (Array.isArray(value)) return value as StudySeasonRow[];
  return mapSeasonsFromApi(payload.seasons as string[] | undefined);
}
