import type { MarkupRule } from "@/modules/pricing/engine";
import { applyMarkup } from "@/modules/pricing/engine";
import type { FlockQuoteLine } from "@/workers/rpa/flock/types";

export type FlockDisplayLine = FlockQuoteLine & {
  markup_amount: number;
  final_total_usd: number;
};

export type FlockStoredQuotes = {
  provider: "flock";
  reference?: string | null;
  lines: FlockDisplayLine[];
};

export function applyMarkupToFlockLines(
  lines: FlockQuoteLine[],
  rule: MarkupRule,
): FlockDisplayLine[] {
  return lines.map((line) => {
    const { markupAmount, finalTotal } = applyMarkup(
      line.totalUsd,
      line.totalUsd,
      rule,
    );
    return {
      ...line,
      markup_amount: markupAmount,
      final_total_usd: finalTotal,
    };
  });
}

export function buildFlockStoredQuotes(
  lines: FlockQuoteLine[],
  rule: MarkupRule,
  reference?: string | null,
): FlockStoredQuotes {
  return {
    provider: "flock",
    reference: reference ?? null,
    lines: applyMarkupToFlockLines(lines, rule),
  };
}

export function parseFlockStoredQuotes(
  json: unknown,
): FlockStoredQuotes | null {
  if (!json || typeof json !== "object" || Array.isArray(json)) {
    return null;
  }
  const o = json as Record<string, unknown>;
  if (o.provider !== "flock" || !Array.isArray(o.lines)) {
    return null;
  }
  return o as unknown as FlockStoredQuotes;
}

export function readFlockShipmentMeta(pickupJson: unknown): {
  pickupDate?: string;
  provider?: string;
} {
  if (!pickupJson || typeof pickupJson !== "object") {
    return {};
  }
  const o = pickupJson as Record<string, unknown>;
  return {
    pickupDate:
      typeof o.flock_pickup_date === "string" ? o.flock_pickup_date : undefined,
    provider: typeof o.provider === "string" ? o.provider : undefined,
  };
}
