import type { Cross, CrossingProject, CrossPollinationEvents, PlannedCross } from "@/lib/api/types.gen";
import type {
  CrossPollinationEventRecord,
  CrossRecord,
  CrossingProjectRecord,
  PlannedCrossRecord,
} from "./types";

const mapPollinationEvent = (event: CrossPollinationEvents, index: number): CrossPollinationEventRecord => {
  const number = event.pollinationNumber ?? null;
  return {
    id: number ? `num:${number}` : `idx:${index}`,
    pollination_number: number,
    pollination_successful: event.pollinationSuccessful ?? null,
    pollination_time_stamp: event.pollinationTimeStamp ? String(event.pollinationTimeStamp).slice(0, 19) : null,
  };
};

export const mapCrossingProject = (project: CrossingProject): CrossingProjectRecord => ({
  id: project.crossingProjectDbId || "",
  crossingProjectDbId: project.crossingProjectDbId || "",
  crossingProjectName: project.crossingProjectName ?? null,
  name: project.crossingProjectName ?? null,
  crossingProjectDescription: project.crossingProjectDescription ?? null,
  description: project.crossingProjectDescription ?? null,
  programDbId: project.programDbId ?? null,
  program_id: project.programDbId ?? null,
  programName: project.programName ?? null,
  program_name: project.programName ?? null,
});

export const mapPlannedCross = (cross: PlannedCross): PlannedCrossRecord => ({
  id: cross.plannedCrossDbId || "",
  plannedCrossDbId: cross.plannedCrossDbId || "",
  plannedCrossName: cross.plannedCrossName ?? null,
  name: cross.plannedCrossName ?? null,
  crossType: cross.crossType ?? null,
  cross_type: cross.crossType ?? null,
  status: cross.status ?? null,
  crossingProjectDbId: cross.crossingProjectDbId ?? null,
  crossing_project_id: cross.crossingProjectDbId ?? null,
  crossingProjectName: cross.crossingProjectName ?? null,
  crossing_project_name: cross.crossingProjectName ?? null,
  planned: true,
  parent1: cross.parent1 ?? null,
  parent2: cross.parent2 ?? null,
});

export const mapCross = (cross: Cross): CrossRecord => ({
  id: cross.crossDbId || "",
  crossDbId: cross.crossDbId || "",
  crossName: cross.crossName ?? null,
  name: cross.crossName ?? null,
  crossType: cross.crossType ?? null,
  cross_type: cross.crossType ?? null,
  crossingProjectDbId: cross.crossingProjectDbId ?? null,
  crossing_project_id: cross.crossingProjectDbId ?? null,
  crossingProjectName: cross.crossingProjectName ?? null,
  crossing_project_name: cross.crossingProjectName ?? null,
  plannedCrossDbId: cross.plannedCrossDbId ?? null,
  planned_cross_id: cross.plannedCrossDbId ?? null,
  plannedCrossName: cross.plannedCrossName ?? null,
  planned: false,
  parent1: cross.parent1 ?? null,
  parent2: cross.parent2 ?? null,
  pollination_events: (cross.pollinationEvents ?? []).map(mapPollinationEvent),
});
