/**
 * 전용 양식별 한글 필드 라벨 매핑
 *
 * DynamicDocument에서 영문 필드키 대신 한글 라벨을 표시하기 위한 공통 모듈.
 * DocumentCreate의 getPreviewData()와 각 Box의 convertToModalData()에서 공유.
 */

// 미리보기에서 숨길 내부 필드 (ID, 시스템 값)
const HIDDEN_FIELDS = new Set([
  'employeeId',
  'vendorId',
  'autoTax',
]);

/** 공문서 */
const officialDocumentLabels: Record<string, string> = {
  documentNumber: '문서번호',
  documentDate: '문서일자',
  recipient: '수신',
  reference: '참조',
  title: '제목',
  body: '본문',
  attachment: '붙임',
  companyName: '회사명',
  representativeName: '대표자명',
  address: '주소',
  phone: '전화',
  fax: '팩스',
  email: '이메일',
};

/** 사직서 */
const resignationLabels: Record<string, string> = {
  department: '부서',
  position: '직위',
  employeeName: '성명',
  residentNumber: '주민등록번호',
  joinDate: '입사일',
  resignDate: '퇴사일',
  employeeAddress: '주소',
  reasonType: '사직사유',
  reasonDetail: '사유상세',
  submitDate: '제출일',
};

/** 재직증명서 */
const employmentCertLabels: Record<string, string> = {
  employeeName: '성명',
  residentNumber: '주민등록번호',
  employeeAddress: '주소',
  companyName: '회사명',
  businessNumber: '사업자등록번호',
  department: '부서',
  position: '직위',
  employmentPeriodStart: '재직기간 시작',
  employmentPeriodEnd: '재직기간 종료',
  purpose: '용도',
  issueDate: '발급일',
};

/** 경력증명서 */
const careerCertLabels: Record<string, string> = {
  employeeName: '성명',
  residentNumber: '주민등록번호',
  birthDate: '생년월일',
  employeeAddress: '주소',
  companyName: '회사명',
  businessNumber: '사업자등록번호',
  representativeName: '대표자명',
  companyPhone: '회사전화',
  companyAddress: '회사주소',
  department: '부서',
  positionTitle: '직위/직책',
  workPeriodStart: '근무기간 시작',
  workPeriodEnd: '근무기간 종료',
  duties: '담당업무',
  purpose: '용도',
  issueDate: '발급일',
};

/** 위촉증명서 */
const appointmentCertLabels: Record<string, string> = {
  employeeName: '성명',
  residentNumber: '주민등록번호',
  department: '부서',
  phone: '연락처',
  appointmentPeriodStart: '위촉기간 시작',
  appointmentPeriodEnd: '위촉기간 종료',
  contractQualification: '계약자격',
  purpose: '용도',
  issueDate: '발급일',
};

/** 사용인감계 */
const sealUsageLabels: Record<string, string> = {
  sealImprint: '인감날인',
  purpose: '사용목적',
  submitTo: '제출처',
  attachedDocuments: '첨부서류',
  usageDate: '사용일',
  companyName: '회사명',
  businessNumber: '사업자등록번호',
  address: '주소',
  representativeName: '대표자명',
};

/** 연차촉진 1차 */
const leaveNotice1stLabels: Record<string, string> = {
  department: '부서',
  position: '직위',
  totalDays: '총 연차일수',
  usedDays: '사용일수',
  remainingDays: '잔여일수',
  deadline: '사용기한',
  legalNotice: '법적고지',
};

/** 연차촉진 2차 */
const leaveNotice2ndLabels: Record<string, string> = {
  department: '부서',
  position: '직위',
  remainingDays: '잔여일수',
  designatedDates: '지정일자',
  legalNotice: '법적고지',
};

/** 위임장 */
const powerOfAttorneyLabels: Record<string, string> = {
  principalCompanyName: '위임자 회사명',
  principalBusinessNumber: '위임자 사업자등록번호',
  principalAddress: '위임자 주소',
  principalRepresentative: '위임자 대표자',
  agentName: '대리인 성명',
  agentBirthDate: '대리인 생년월일',
  agentAddress: '대리인 주소',
  agentPhone: '대리인 연락처',
  agentDepartment: '대리인 소속부서',
  delegationDetails: '위임사항',
  delegationPeriodStart: '위임기간 시작',
  delegationPeriodEnd: '위임기간 종료',
  attachedDocuments: '첨부서류',
};

/** 이사회의사록 */
const boardMinutesLabels: Record<string, string> = {
  meetingDate: '회의일시',
  meetingPlace: '회의장소',
  totalDirectors: '이사 총원',
  attendingDirectors: '출석 이사',
  totalAuditors: '감사 총원',
  attendingAuditors: '출석 감사',
  agendaTitle: '의안',
  agendaResult: '의결결과',
  chairperson: '의장',
  proceedings: '회의내용',
  adjournmentTime: '폐회시간',
  signatories: '서명인',
};

/** 견적서 */
const quotationLabels: Record<string, string> = {
  recipientName: '수신',
  quotationDate: '견적일자',
  businessNumber: '사업자등록번호',
  companyName: '회사명',
  representativeName: '대표자명',
  companyAddress: '회사주소',
  businessType: '업태',
  businessCategory: '종목',
  companyPhone: '전화',
  accountNumber: '계좌번호',
  items: '견적항목',
  specialNotes: '특기사항',
};

// 동적 폼: 근태신청
const attendanceRequestLabels: Record<string, string> = {
  user_name: '신청자',
  request_type: '신청유형',
  period: '기간',
  days: '일수',
  reason: '사유',
};

// 동적 폼: 사유서
const reasonReportLabels: Record<string, string> = {
  user_name: '작성자',
  report_type: '사유유형',
  target_date: '대상일',
  reason: '사유',
};

// 동적 폼: 품의서 (proposal은 전용 폼이지만 content 키가 영문일 수 있음)
const proposalLabels: Record<string, string> = {
  title: '제목',
  vendor: '거래처',
  description: '내용',
  reason: '사유',
  estimatedCost: '예상비용',
};

/** 양식코드 → 한글 라벨 맵 */
const FORM_FIELD_LABELS: Record<string, Record<string, string>> = {
  attendance_request: attendanceRequestLabels,
  reason_report: reasonReportLabels,
  proposal: proposalLabels,
  officialDocument: officialDocumentLabels,
  official_letter: officialDocumentLabels,
  resignation: resignationLabels,
  employmentCert: employmentCertLabels,
  employment_cert: employmentCertLabels,
  careerCert: careerCertLabels,
  career_cert: careerCertLabels,
  appointmentCert: appointmentCertLabels,
  appointment_cert: appointmentCertLabels,
  sealUsage: sealUsageLabels,
  seal_usage: sealUsageLabels,
  leaveNotice1st: leaveNotice1stLabels,
  leave_promotion_1st: leaveNotice1stLabels,
  leaveNotice2nd: leaveNotice2ndLabels,
  leave_promotion_2nd: leaveNotice2ndLabels,
  powerOfAttorney: powerOfAttorneyLabels,
  delegation: powerOfAttorneyLabels,
  boardMinutes: boardMinutesLabels,
  board_minutes: boardMinutesLabels,
  quotation: quotationLabels,
};

/** 양식코드 → 한글 양식명 */
const FORM_NAME_MAP: Record<string, string> = {
  attendance_request: '근태신청',
  reason_report: '사유서',
  proposal: '품의서',
  officialDocument: '공문서',
  official_letter: '공문서',
  resignation: '사직서',
  employmentCert: '재직증명서',
  employment_cert: '재직증명서',
  careerCert: '경력증명서',
  career_cert: '경력증명서',
  appointmentCert: '위촉증명서',
  appointment_cert: '위촉증명서',
  sealUsage: '사용인감계',
  seal_usage: '사용인감계',
  leaveNotice1st: '연차촉진 1차',
  leave_promotion_1st: '연차촉진 1차',
  leaveNotice2nd: '연차촉진 2차',
  leave_promotion_2nd: '연차촉진 2차',
  powerOfAttorney: '위임장',
  delegation: '위임장',
  boardMinutes: '이사회의사록',
  board_minutes: '이사회의사록',
  quotation: '견적서',
  expenseReport: '지출결의서',
  expense_report: '지출결의서',
  expenseEstimate: '비용견적서',
  expense_estimate: '비용견적서',
};

/**
 * 양식코드에 해당하는 필드 라벨 맵 반환
 */
export function getFieldLabels(formCode: string): Record<string, string> | undefined {
  return FORM_FIELD_LABELS[formCode];
}

/**
 * 양식코드에 해당하는 한글 양식명 반환
 */
export function getFormName(formCode: string): string {
  return FORM_NAME_MAP[formCode] || formCode;
}

/**
 * 미리보기에서 숨길 내부 필드인지 확인
 */
export function isHiddenField(key: string): boolean {
  return HIDDEN_FIELDS.has(key);
}

/**
 * fields에서 숨길 필드를 제거한 새 객체 반환
 */
export function filterVisibleFields(fields: Record<string, unknown>): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(fields)) {
    if (!HIDDEN_FIELDS.has(key)) {
      result[key] = value;
    }
  }
  return result;
}
