import { Injectable } from '@nestjs/common';
import { RegistrationWorkflowStage, WorkflowStage } from 'src/common/entities';
import { RegistrationWorkflowStageRepository } from '../repositories/registration-workflow-stage.repository';
import { handleKnownErrors } from 'src/common/utils/handle-error.util';
import { ERROR_CODES } from 'src/common/constants/error-string-constants';

@Injectable()
export class RegistrationWorkflowStageService {
  constructor(private readonly registrationWorkflowStageRepository: RegistrationWorkflowStageRepository) {}

  async getByRegistrationId(registrationId: number): Promise<RegistrationWorkflowStage[]> {
    try {
      return await this.registrationWorkflowStageRepository.findByRegistrationId(registrationId);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_REGISTRATION_STAGE_GET_FAILED, error);
    }
  }

  async getByMultipleRegistrationIds(registrationIds: number[]): Promise<RegistrationWorkflowStage[]> {
    try {
      return await this.registrationWorkflowStageRepository.findByMultipleRegistrationIds(registrationIds);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_REGISTRATION_STAGE_GET_FAILED, error);
    }
  }

  async getActiveStageByRegistrationId(registrationId: number): Promise<RegistrationWorkflowStage | null> {
    try {
      return await this.registrationWorkflowStageRepository.findActiveByRegistrationId(registrationId);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_REGISTRATION_STAGE_GET_FAILED, error);
    }
  }

  async upsertByStageKey(registrationId: number, stageKey: string, status: string, userId?: number): Promise<RegistrationWorkflowStage> {
    try {
      return await this.registrationWorkflowStageRepository.upsertByStageKey(registrationId, stageKey, status, userId);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_REGISTRATION_STAGE_SAVE_FAILED, error);
    }
  }

}