import { type PageStatus } from '@defra/forms-model'

import { getCacheService } from '../helpers.js'
import { type FormModel } from '../models/index.js'
import { QuestionPageController } from './QuestionPageController.js'
import { type FormContext } from '../types.js'
import {
  type FormRequest,
  type FormResponseToolkit
} from '../../../routes/types.js'

export class StatusPageController extends QuestionPageController {
  declare pageDef: PageStatus
  allowSaveAndExit = false
  showReferenceNumber = false

  constructor(model: FormModel, pageDef: PageStatus) {
    super(model, pageDef)
    this.viewName = 'confirmation'
    this.showReferenceNumber = model.def.options?.showReferenceNumber ?? false
  }

  getRelevantPath() {
    return this.getStatusPath()
  }

  makeGetRouteHandler() {
    return async (
      request: FormRequest,
      context: FormContext,
      h: FormResponseToolkit
    ) => {
      const { viewModel, viewName } = this

      const cacheService = getCacheService(request.server)
      const confirmationState = await cacheService.getConfirmationState(request)

      // If there's no confirmation state, then
      // redirect the user back to the start of the form
      if (!confirmationState.confirmed) {
        return this.proceed(request, h, this.getStartPath())
      }

      const slug = request.params.slug
      const { formsService } = this.model.services
      const { getFormMetadata, getFormMetadataById } = formsService

      const { submissionGuidance } = await getFormMetadata(slug)

      // Re-read form name if overriding display (for example, in a feedback form)
      const storedFormId = confirmationState.formId
      const formName = storedFormId
        ? (await getFormMetadataById(storedFormId)).title
        : undefined

      return h.view(viewName, {
        ...viewModel,
        submissionGuidance,
        formName,
        showReferenceNumber: this.showReferenceNumber,
        referenceNumber: confirmationState.referenceNumber
      })
    }
  }
}
