class Admin::Legacy::HumanResources::Employees::PhonesController <
    Admin::Legacy::HumanResources::Controller
  def index
    employee.sync_legacy_phones
    render_success :ok, json: phones.map { |p| phone_props(p) }
  end

  def show
    render_success :ok, json: phone_props(phone)
  end

  def create
    phone = phones.build(phone_params)
    if phone.save
      render_success :ok, json: phone_props(phone)
    else
      render_error :unprocessable_entity, errors: phone
    end
  end

  def update
    if phone.update(phone_params)
      render_success :ok, json: phone_props(phone)
    else
      render_error :unprocessable_entity, errors: phone
    end
  end

  def destroy
    if phone.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: phone
    end
  end

  def available
    render_success :ok, json: employee.available_phones(params[:types] || [])
  end

  private
    def permissions
      if [:index, :show, :available].include?(action_name.to_sym)
        ['read', 'write', 'manage']
      else
        ['write', 'manage']
      end
    end

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

    def phones
      employee.phones
    end

    def phone
      @phone ||= phones.find_by(id: params[:id])
    end

    def phone_params
      params.permit(:code, :country_code, :number, :extension)
    end

    def phone_props(phone)
      {
        id: phone.id,
        code: phone.code,
        country_code: phone.country_code,
        number: phone.number,
        extension: phone.extension,
        full_name: employee.full_name
      }
    end
end
