import { Prisma, PlannedTime, PlannedTimeStaging } from '@prisma/client';

export class PlannedTimeLoader {
  public static determineLoadOperations(
    stagingPlannedTimes: PlannedTimeStaging[],
    finalPlannedTimes: PlannedTime[],
  ): {
    deleted: string[];
    updated: Prisma.PlannedTimeCreateInput[];
    created: Prisma.PlannedTimeCreateInput[];
  } {
    const deletedPlannedTimes = stagingPlannedTimes.filter(
      ({ deleted }) => deleted,
    );
    const plannedTimesToInsert = stagingPlannedTimes.filter(
      ({ id }) =>
        !!id &&
        !deletedPlannedTimes.find(
          (deletedPlannedTime) => deletedPlannedTime.id === id,
        ),
    );
    const newPlannedTimes: Prisma.PlannedTimeCreateInput[] = [];
    const updatedPlannedTimes: Prisma.PlannedTimeCreateInput[] = [];
    for (const stagingPlannedTime of plannedTimesToInsert) {
      const finalPlannedTime = finalPlannedTimes.find(
        (finalPlannedTime) =>
          finalPlannedTime.id === `${stagingPlannedTime.id}`,
      );
      if (finalPlannedTime) {
        updatedPlannedTimes.push(
          this.plannedTimeStagingToFinal(stagingPlannedTime),
        );
      } else {
        newPlannedTimes.push(
          this.plannedTimeStagingToFinal(stagingPlannedTime),
        );
      }
    }

    return {
      deleted: deletedPlannedTimes.map(({ id }) => `${id}`),
      updated: updatedPlannedTimes,
      created: newPlannedTimes,
    };
  }

  private static plannedTimeStagingToFinal(
    plannedtime: PlannedTimeStaging,
  ): Prisma.PlannedTimeCreateInput {
    const {
      id,
      employeeId,
      firstname,
      surname,
      departmentName,
      startDate,
      endDate,
      mark,
    } = plannedtime;

    return {
      firstname,
      surname,
      startDate,
      endDate,
      id: `${id}`,
      userId: `${employeeId}`,
      department: departmentName,
      pause: 0,
      duration: 0,
      note: mark,
    };
  }
}
