import type { Prisma } from "@capakraken/db";
import type { AssignmentBookingWithFallback } from "./list-assignment-bookings.js";

type ChargeabilityProjectLike = AssignmentBookingWithFallback["project"];
type ChargeabilityBookingLike = Pick<AssignmentBookingWithFallback, "status" | "project">;

function asObject(value: Prisma.JsonValue | null | undefined): Record<string, unknown> | null {
  if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value)) {
    return null;
  }

  return value as Record<string, unknown>;
}

export function isImportedTbdDraftProject(project: ChargeabilityProjectLike): boolean {
  if (project.status !== "DRAFT") {
    return false;
  }

  const dynamicFields = asObject(project.dynamicFields);
  const dispoImport = asObject(dynamicFields?.["dispoImport"] as Prisma.JsonValue | undefined);
  return dispoImport?.["isTbd"] === true;
}

export function isChargeabilityRelevantProject(
  project: ChargeabilityProjectLike,
  includeProposed: boolean,
): boolean {
  if (project.status === "ACTIVE") {
    return true;
  }

  if (project.status === "CANCELLED") {
    return false;
  }

  return includeProposed && isImportedTbdDraftProject(project);
}

export function isChargeabilityActualBooking(
  booking: ChargeabilityBookingLike,
  includeProposed: boolean,
): boolean {
  if (!isChargeabilityRelevantProject(booking.project, includeProposed)) {
    return false;
  }

  return (
    booking.status === "CONFIRMED" ||
    booking.status === "ACTIVE" ||
    (includeProposed && booking.status === "PROPOSED")
  );
}
