import type { AlertLog } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { buildAlertPresentation } from "@/modules/alert/alert-presentation";
import type { AlertType } from "@/modules/alert/types";

export function serializeAlert(record: AlertLog) {
  return {
    id: String(record.id),
    alert_type: record.alertType,
    quote_id: record.quoteId,
    cargo_hash: record.cargoHash,
    detail_json: record.detailJson,
    status: record.status,
    resolver_id: record.resolverId,
    resolved_at: record.resolvedAt?.toISOString() ?? null,
    created_at: record.createdAt.toISOString(),
  };
}

export async function serializeAlertEnriched(record: AlertLog) {
  const quote = record.quoteId
    ? await prisma.quoteRecord.findUnique({
        where: { quoteId: record.quoteId },
      })
    : null;

  const presentation = buildAlertPresentation(
    record.alertType as AlertType,
    record.detailJson,
    quote,
  );

  return {
    ...serializeAlert(record),
    ...presentation,
  };
}
