"use client";

import { bookingHasManualTotalPrice, calculateBookingTotalPrice, roundCurrency, type RentalBooking } from "@rental/shared";

export const parsePriceInput = (value: string) => {
  const normalized = value.trim().replace(",", ".");

  if (normalized === "") {
    return null;
  }

  const parsed = Number(normalized);

  if (!Number.isFinite(parsed) || parsed < 0) {
    return null;
  }

  return roundCurrency(parsed);
};

export const formatPriceInput = (value?: number | null) => {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    return "";
  }

  return value.toFixed(2).replace(".", ",");
};

export const getAutomaticTotalPriceValue = (startDate: string, endDate: string, dayRateInput: string) =>
  calculateBookingTotalPrice(startDate, endDate, parsePriceInput(dayRateInput));

export const bookingUsesManualTotalPrice = (
  booking: Pick<RentalBooking, "startDate" | "endDate" | "dayRate" | "totalPrice">
) => bookingHasManualTotalPrice(booking);
