import { Injectable } from '@nestjs/common';
import { WorkflowConfiguration } from 'src/common/entities';
import { ERROR_CODES } from 'src/common/constants/error-string-constants';
import { InifniNotFoundException } from 'src/common/exceptions/infini-notfound-exception';
import { WorkflowConfigurationRepository } from '../repositories/workflow-configuration.repository';
import { handleKnownErrors } from 'src/common/utils/handle-error.util';

@Injectable()
export class WorkflowConfigurationService {
  constructor(private readonly workflowConfigurationRepository: WorkflowConfigurationRepository) {}

  async getWorkflowByProgramType(programTypeKey: string): Promise<WorkflowConfiguration> {
    try {
      const workflow = await this.workflowConfigurationRepository.findActiveByProgramTypeKey(programTypeKey);
      if (!workflow) {
        throw new InifniNotFoundException(ERROR_CODES.WORKFLOW_CONFIGURATION_NOTFOUND, null, null, programTypeKey);
      }
      return workflow;
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_CONFIGURATION_GET_FAILED, error);
    }
  }

  async findByWorkflowKey(workflowKey: string): Promise<WorkflowConfiguration | null> {
    try {
      return await this.workflowConfigurationRepository.findByWorkflowKey(workflowKey);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_CONFIGURATION_GET_FAILED, error);
    }
  }

  async findById(id: number): Promise<WorkflowConfiguration | null> {
    try {
      return await this.workflowConfigurationRepository.findById(id);
    } catch (error) {
      handleKnownErrors(ERROR_CODES.WORKFLOW_CONFIGURATION_GET_FAILED, error);
    }
  }
}
