module Suppliers
  class EmployeeShiftsController < Suppliers::ApplicationController
    def index
      @employee_shifts = EmployeeShift.for_supplier(current_supplier, relevant_from: 1.week.ago)
      #@employee_shifts.include_relations(:employee, :supplier)
      # Only select shifts from currently linked and employees
      #@employee_shifts.select! do |shift|
      #  return false unless current_supplier.employee_ids.include?(shift.employee.try(:id))
      #  shift.employee.enrich_with_settings current_supplier.settings_for(shift.employee)
      #  true
      #end
      #@employee_shifts.each { |shift| shift.employee.enrich_with_settings current_supplier.settings_for(shift.employee)
      render json: @employee_shifts
    end
    def create
      @employee_shift = EmployeeShift.new(employee_shift_params)
      @employee_shift.supplier = current_supplier
      @employee_shift.save
      render json: @employee_shift
    end

    def update
      @employee_shift = EmployeeShift.find_by_supplier_id_and_id!(current_supplier.id, params[:id])
      @employee_shift.update employee_shift_params
      render json: @employee_shift
    end

    def destroy
      @employee_shift = EmployeeShift.find_by_supplier_id_and_id!(current_supplier.id, params[:id])
      head :forbidden and return unless @employee_shift.supplier_id == current_supplier.id
      @employee_shift= EmployeeShift.find_by_supplier_id_and_id!(current_supplier.id, params[:id])
      @employee_shift.destroy
      head :no_content
    end

    private

    def employee_shift_params
      permitted_attributes = [:start_from, :end_on, :employee_id, :description, :full_day]
      # do not raise in development and test for json communication
      result = if request.format.json?
        params.require(:employee_shift).slice(*permitted_attributes).permit!
      else
        params.require(:employee_shift).permit permitted_attributes
      end
    end
  end
end
