import type { AtsEvent } from "@/components/eventStream";

export const APPLICANT_STAGE_LABELS: Record<string, string> = {
  new_applied: "New/Applied",
  resume_review_screening: "Resume Review / Screening",
  offer_letter_sent: "Offer Letter Sent",
  hired_or_closed: "Hired or Closed",
};

type RecruiterEventDisplay = {
  title: string;
  detail: string;
};

function getStringValue(value: unknown, fallback: string) {
  return typeof value === "string" ? value : fallback;
}

function formatStage(stageId: unknown) {
  if (typeof stageId !== "string") {
    return "Unknown stage";
  }
  return APPLICANT_STAGE_LABELS[stageId] ?? stageId;
}

type EventFormatter = (event: AtsEvent) => RecruiterEventDisplay;

const recruiterEventFormatters: Record<string, EventFormatter> = {
  PositionDeclared: (event) => {
    const title = getStringValue(event.payload.title, "Position");
    const department = getStringValue(event.payload.department, "Department");
    const location = getStringValue(event.payload.location, "");
    return {
      title: "Position opened",
      detail: location ? `${title} was opened in ${department} (${location}).` : `${title} was opened for ${department}.`,
    };
  },
  ApplicantDeclared: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    return {
      title: "Applicant added",
      detail: `${applicantName} entered the pipeline at ${formatStage(event.payload.stageId)}.`,
    };
  },
  ApplicantStageMoved: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    return {
      title: "Applicant stage updated",
      detail: `${applicantName} moved from ${formatStage(
        event.payload.fromStageId
      )} to ${formatStage(event.payload.toStageId)}.`,
    };
  },
  CandidatePipelineReportGenerated: () => ({
    title: "Candidate Pipeline Report Generated",
    detail: "A manager generated and downloaded the current candidate pipeline report.",
  }),
  ApplicantOfferLetterInitiated: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const positionTitle = getStringValue(event.payload.positionTitle, "selected role");
    return {
      title: "Offer letter preparation started",
      detail: `${applicantName} was selected to receive an offer letter for ${positionTitle}.`,
    };
  },
  ApplicantOfferLetterSent: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const positionTitle = getStringValue(event.payload.positionTitle, "selected role");
    const hasEmbeddedSessionUrl =
      typeof event.payload.embeddedSessionURL === "string" &&
      event.payload.embeddedSessionURL.length > 0;
    return {
      title: "Offer letter sent",
      detail: hasEmbeddedSessionUrl
        ? `${applicantName} was sent an offer letter for ${positionTitle} and an embedded eSign session was created.`
        : `${applicantName} was sent an offer letter for ${positionTitle}.`,
    };
  },
  ApplicantOfferLetterStatusUpdated: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const currentStatus = getStringValue(event.payload.currentStatus, "Unknown");
    return {
      title: "Offer letter signing status refreshed",
      detail: `Latest eSign status for ${applicantName} is now ${currentStatus}.`,
    };
  },
  ApplicantScreeningInitiated: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    return {
      title: "AI screening process started",
      detail: `Initial AI screening started for ${applicantName}.`,
    };
  },
  ApplicantScreeningPolicyModified: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    return {
      title: "AI screening policy updated",
      detail: `Evaluation policy was updated before AI screening ${applicantName}.`,
    };
  },
  ApplicantScreeningEvaluationCompleted: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const policyId = getStringValue(event.payload.policyId, "Unknown policy");
    const scoreRaw = event.payload.overallFitScore;
    const score =
      typeof scoreRaw === "number" || typeof scoreRaw === "string" ? String(scoreRaw) : "Unknown";
    return {
      title: "AI screening evaluation completed",
      detail: `AI screening completed for ${applicantName} with fit score ${score} using ${policyId}.`,
    };
  },
  ApplicantScreeningEvaluationFailed: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    return {
      title: "AI screening evaluation failed",
      detail: `AI screening could not be completed for ${applicantName}.`,
    };
  },
  ApplicantScorecardSubmitted: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const recommendation = getStringValue(event.payload.recommendation, "unspecified");
    const ratingRaw = event.payload.rating;
    const rating =
      typeof ratingRaw === "number" || typeof ratingRaw === "string"
        ? String(ratingRaw)
        : "Unknown";
    const friendlyRecommendation =
      recommendation === "strong_hire"
        ? "Strong Hire"
        : recommendation === "no_hire"
        ? "No Hire"
        : recommendation === "hire"
        ? "Hire"
        : recommendation;
    return {
      title: "Scorecard saved",
      detail: `${applicantName} scorecard recorded with recommendation ${friendlyRecommendation} and rating ${rating}.`,
    };
  },
  ApplicantHireCloseDecisionMade: (event) => {
    const applicantName = getStringValue(event.payload.applicantName, "Applicant");
    const disposition = getStringValue(event.payload.disposition, "closed");
    const outcomeText = disposition === "hired" ? "marked as hired" : "closed out";
    return {
      title: "Final hiring outcome recorded",
      detail: `${applicantName} was ${outcomeText}.`,
    };
  },
};

export function formatEventForRecruiter(event: AtsEvent): RecruiterEventDisplay {
  const formatter = recruiterEventFormatters[event.eventType];
  if (!formatter) {
    return {
      title: event.eventType,
      detail: "Recruiting activity recorded.",
    };
  }
  return formatter(event);
}
