class Admin::Legacy::HumanResources::Employees::Indiana::IdentitiesController <
  Admin::Legacy::HumanResources::Controller
  def index
    render_success :ok, json: identity_service.search.map { |r| search_props(r) }
  end

  def show
    render_success :ok, json: identity_service.find(params[:id])
  end

  def create
    response = identity_service.create
    if response[:success]
      render_success :ok, json: response
    else
      render_error :unprocessable_entity, json: response
    end
  end

  def processing_status
    data = params[:refresh]&.to_bool ? identity : identity_service.processing_status
    render_success :ok, json: data
  end

  def missing_information
    render_success :ok, json: identity_service.missing_information
  end

  private
    def employee
      @employee ||= current_school.employees.find_by(id: params[:employee_id])
    end

    def identity
      @identity ||= employee.find_or_build_ed_fi_identity
    end

    def identity_service
      dir = "#{current_school.indiana_environment_service}::StaffIdentityService"
      dir.constantize.new(current_school_year.id, employee: employee)
    end

    def search_props(response)
      return {} if response.nil? || response['identityStatus'] == 'Inactive'

      {
        id: response['schoolPersonnelNumber'],
        first_name: response['firstName'],
        last_name: response['lastSurname'],
        middle_name: response['middleName'],
        birth_date: response['birthDate'].to_date,
        gender: response['sex']
      }
    end
end
