import type { MarketingMeetingStatus, Prisma } from "@prisma/client";
import type { Meeting, MeetingCommitment } from "@/lib/marketing";

export function parseStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0).map((item) => item.trim());
}

export function parseMeetingStatus(value: unknown): MarketingMeetingStatus | null {
  if (value === "requested" || value === "scheduled" || value === "completed" || value === "cancelled") {
    return value;
  }

  return null;
}

export function mapMeetingCommitment(commitment: {
  id: string;
  title: string;
  description: string | null;
  ownerName: string | null;
  dueDate: Date | null;
  status: string;
}): MeetingCommitment {
  return {
    id: commitment.id,
    title: commitment.title,
    description: commitment.description,
    ownerName: commitment.ownerName,
    dueDate: commitment.dueDate ? commitment.dueDate.toISOString() : null,
    status: commitment.status,
  };
}

export function mapMeeting(record: {
  id: string;
  title: string;
  status: MarketingMeetingStatus;
  agenda: string;
  requestedById: string | null;
  participantNames: Prisma.JsonValue;
  suggestedTimes: Prisma.JsonValue;
  scheduledFor: Date | null;
  completedAt: Date | null;
  commitments: Array<{
    id: string;
    title: string;
    description: string | null;
    ownerName: string | null;
    dueDate: Date | null;
    status: string;
  }>;
}): Meeting {
  return {
    id: record.id,
    title: record.title,
    status: record.status,
    agenda: record.agenda,
    requestedById: record.requestedById,
    participantNames: parseStringArray(record.participantNames),
    suggestedTimes: parseStringArray(record.suggestedTimes),
    scheduledFor: record.scheduledFor ? record.scheduledFor.toISOString() : null,
    completedAt: record.completedAt ? record.completedAt.toISOString() : null,
    commitments: record.commitments.map(mapMeetingCommitment),
  };
}
