import type { DB } from '@heygermany/sdk'
import {
  DocumentStatuses,
  LanguageLevels,
  NurseRecognitionGermanyValues,
  type GetCandidateResult,
  type QualificationCard,
} from '@heygermany/sdk'
import type { TranslationService } from "../services/translation-service.js"

export const createCandidateCardEngine = (translation: TranslationService, locale: string) => ({
  constants: {},

  // ============= EDUCATION =============
  education: {
    // Completed if all 3 are true; otherwise Required.
    rules: [
      {
        id: "education_completed",
        when: {
          and: [
            { "==": [{ var: "nursingRelatedDegree" }, true] },
            { "==": [{ var: "accreditedUniversity" }, true] },
            { "==": [{ var: "structuredTraining.overallStatus" }, true] },
          ],
        },
        status: "completed",
      },
      {
        id: "education_required",
        when: { "!!": true }, // fallback
        status: "required",
      },
    ],
    // Next step priority: 1 > 3 > 2 (show only one)
    pickNextStep(candidate: GetCandidateResult): string | undefined {
      const missDegree = candidate.nursingRelatedDegree === false
      const missStructured = candidate.structuredTraining.overallStatus === false
      const missAccredited = candidate.accreditedUniversity === false

      if (missDegree) {
        return translation.t('education.steps.missdegree', locale)
      }
      if (missStructured) {
        return translation.t('education.steps.missstructured', locale)
      }
      if (missAccredited) {
        return translation.t('education.steps.missaccredited', locale)
      }
      return undefined
    },
    getRequirements(): string[] {
      return translation.tArray('education.requirements', locale)
    },
    getCompletedDescription(): string {
      return translation.t('education.completeddescription', locale)
    },
    getRequiredDescription(): string {
      return translation.t('education.requireddescription', locale)
    },
  },

  // ============= LANGUAGE =============
  language: {
    build(candidate: GetCandidateResult): QualificationCard {
      const LEVEL_RANK: Record<DB.LanguageLevel, number> = {
        A_ONE: 1, A_TWO: 2, B_ONE: 3, B_TWO: 4, C_ONE: 5, C_TWO: 6, NONE: 0
      }
      const REQUIRED_GERMAN_BY_ROLE: Record<DB.NurseRecognitionGermany, DB.LanguageLevel> = {
        [NurseRecognitionGermanyValues.NURSE]: LanguageLevels.B_TWO,
        [NurseRecognitionGermanyValues.ASSISTANT_NURSE]: LanguageLevels.B_ONE,
        [NurseRecognitionGermanyValues.NURSING_HELPER]: LanguageLevels.B_ONE,
      }

      const reqLevel = REQUIRED_GERMAN_BY_ROLE[candidate.qualificationStatusGermany!]
      const req = LEVEL_RANK[reqLevel]
      const skills = LEVEL_RANK[candidate.languageLevel!]
      const meets = skills >= req

      const certUploaded = candidate.docs.language === DocumentStatuses.VERIFIED
      const status: QualificationCard['status'] = meets ? "completed" : "in-progress"

      // progress: requirement == 100%, skills are a share of 100
      const progress = !meets ? Math.max(0, Math.min(100, Math.round((skills / req) * 100))) : undefined

      const requirements = [
        translation.t('language.requirements.germanlevel', locale, { level: reqLevel }),
        translation.t('language.requirements.certificate', locale),
      ]

      // Steps:
      // - If not met: always show both step 1 and 2 together.
      // - If met but no certificate uploaded (i.e., self-assessment only), show the reminder text instead of steps.
      const steps: string[] | undefined = !meets
        ? [
          translation.t('language.steps.improvelevel', locale, {
            currentLevel: candidate.languageLevel || translation.t('language.levelnames.none', locale),
            requiredLevel: reqLevel
          }),
          translation.t('language.steps.getcertificate', locale),
        ]
        : undefined

      const description = translation.t('language.description', locale)

      // Reminder when met via self-assessment, without uploaded certificate
      const reminderWhenMetNoCert =
        meets && !certUploaded
          ? translation.t('language.reminder', locale)
          : undefined

      return {
        title: translation.t('language.title', locale),
        description,
        status,
        progress,
        requirements,
        steps: steps ?? (reminderWhenMetNoCert ? [reminderWhenMetNoCert] : undefined),
      }
    },
  },

  // ============= LICENSE =============
  license: {
    // Completed if license doc uploaded OR license not needed (licenseMandatory = false)
    rules: [
      {
        id: "license_completed",
        when: { "or": [
          { "==": [{ var: "licenseMandatory" }, false] },
          { "==": [{ var: "docs.license" }, DocumentStatuses.VERIFIED] }
        ]},
        status: "completed",
      },
      {
        id: "license_required",
        when: { "!!": true },
        status: "required",
      },
    ],
    getDescriptionCompleted(): string {
      return translation.t('license.descriptioncompleted', locale)
    },
    getDescriptionRequired(): string {
      return translation.t('license.descriptionrequired', locale)
    },
    getRequirements(): string[] {
      return translation.tArray('license.requirements', locale)
    },
    getSteps(): string[] {
      return translation.tArray('license.steps', locale)
    },
  },

  // ============= ADDITIONAL (Experience + Copies + Originals) =============
  additional: {
    experience(candidate: GetCandidateResult): QualificationCard {
      const cvUploaded = candidate.docs.cv === DocumentStatuses.VERIFIED
      return {
        title: translation.t('additional.experience.title', locale),
        description: translation.t('additional.experience.description', locale),
        status: cvUploaded ? "completed" : "optional",
        requirements: translation.tArray('additional.experience.requirements', locale),
        steps: cvUploaded ? undefined : translation.tArray('additional.experience.steps', locale),
      }
    },
    copies(): QualificationCard {
      return {
        title: translation.t('additional.copies.title', locale),
        description: translation.t('additional.copies.description', locale),
        status: "required",
        requirements: translation.tArray('additional.copies.requirements', locale),
        steps: translation.tArray('additional.copies.steps', locale),
      }
    },
    originals(): QualificationCard {
      return {
        title: translation.t('additional.originals.title', locale),
        description: translation.t('additional.originals.description', locale),
        status: "required",
        requirements: translation.tArray('additional.originals.requirements', locale),
        steps: translation.tArray('additional.originals.steps', locale),
      }
    },
  },
})
