import { ExcelColumnDef } from '@/common/excel/excel-export.types';

export type ProgressReportCommentsExportLanguage = 'en' | 'km';

/** One comment row as the export query returns it. */
export type ProgressReportCommentExportItem = {
  id: number;
  comment: unknown;
  createdAt: Date;
  updatedAt: Date;
  commentType: { id: number; name: string } | null;
  user: { id: number; name: string | null } | null;
  progressReportUpdateIssue: {
    ministry: { id: number; name: string } | null;
    issue: { id: number; title: string } | null;
  } | null;
  progressReportUpdatePlenaryDecision: {
    ministry: { id: number; name: string } | null;
    plenaryDecision: { id: number; decision: string } | null;
  } | null;
};

const EXPORT_COLUMN_KEYS = [
  'no',
  'ministry',
  'subject',
  'commentType',
  'comment',
] as const;

type ExportColumnKey = (typeof EXPORT_COLUMN_KEYS)[number];

const EXPORT_HEADERS: Record<
  ProgressReportCommentsExportLanguage,
  Record<ExportColumnKey, string>
> = {
  en: {
    no: 'No',
    ministry: 'Ministry',
    subject: 'Issue / RGC Decision',
    commentType: 'Comment Type',
    comment: 'Comment',
  },
  km: {
    no: 'ល.រ',
    ministry: 'ក្រសួង',
    subject: 'បញ្ហា / សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល',
    commentType: 'ប្រភេទមតិយោបល់',
    comment: 'មតិយោបល់',
  },
};

const EXPORT_COLUMN_WIDTHS: Record<ExportColumnKey, number> = {
  no: 6,
  ministry: 18,
  subject: 46,
  commentType: 22,
  comment: 60,
};

const EMPTY_CELL = '-';

export function getProgressReportCommentsExportColumns(
  lang: ProgressReportCommentsExportLanguage = 'en',
): ExcelColumnDef[] {
  const headers = EXPORT_HEADERS[lang];

  return EXPORT_COLUMN_KEYS.map((key) => ({
    key,
    header: headers[key],
    width: EXPORT_COLUMN_WIDTHS[key],
  }));
}

/**
 * The comment column is JSON. A plain string is used as-is; anything else is
 * stringified, and an empty comment leaves the cell blank rather than writing
 * the text "null".
 */
function toCommentText(comment: unknown): string {
  if (comment === null || comment === undefined) return EMPTY_CELL;
  if (typeof comment === 'string') return comment.trim() || EMPTY_CELL;

  return JSON.stringify(comment);
}

export function mapProgressReportCommentToExportRow(
  comment: ProgressReportCommentExportItem,
  index: number,
): Record<string, string | number> {
  const issueParent = comment.progressReportUpdateIssue;
  const decisionParent = comment.progressReportUpdatePlenaryDecision;

  const ministry =
    issueParent?.ministry?.name ?? decisionParent?.ministry?.name ?? EMPTY_CELL;
  const subject =
    issueParent?.issue?.title ??
    decisionParent?.plenaryDecision?.decision ??
    EMPTY_CELL;

  return {
    no: index + 1,
    ministry,
    subject: subject.trim() || EMPTY_CELL,
    commentType: comment.commentType?.name?.trim() || EMPTY_CELL,
    comment: toCommentText(comment.comment),
  };
}

export function buildProgressReportCommentsExportFilename(
  progressReportId: number,
  ministryName?: string,
): string {
  const today = new Date().toISOString().slice(0, 10);
  // Keep the ministry out of the name when the file covers the whole report.
  const ministry = ministryName?.trim()
    ? `-${ministryName.trim().replace(/[^\p{L}\p{N}-]+/gu, '_')}`
    : '';

  return `progress-report-${progressReportId}${ministry}-comments-${today}.xlsx`;
}
