class TaskListsController < ApplicationController

  before_action :ensure_valid_user
  before_action :set_task_list, only: [:show, :update, :destroy, :add_recipe]

  def index
    @task_lists = TaskList.for_user(current_user).includes(:task_items).order(created_at: :desc)
    render json: TaskListSerializer.for(@task_lists)
  end

  def show
    ensure_owner(@task_list)
    render json: TaskListSerializer.for(@task_list)
  end

  def create
    @task_list = TaskList.new(task_list_params)
    @task_list.user = current_user

    if @task_list.save
      render json: TaskListSerializer.for(@task_list), status: :created, location: @task_list
    else
      render json: @task_list.errors, status: :unprocessable_entity
    end
  end

  def update
    ensure_owner(@task_list) do
      if @task_list.update(task_list_params)
        TaskChannel.update_task_list(@task_list)
        render json: TaskListSerializer.for(@task_list), status: :ok, location: @task_list
      else
        render json: @task_list.errors, status: :unprocessable_entity
      end
    end
  end

  def destroy
    ensure_owner(@task_list) do
      @task_list.destroy
      head :no_content
    end
  end

  def add_recipe
    ensure_owner(@task_list) do
      recipe = Recipe.find(params[:recipe_id])

      @task_list.add_recipe_ingredients(recipe)
      TaskChannel.update_task_list(@task_list)

      head :no_content
    end
  end

  private

  def task_list_params
    params.require(:task_list).permit(:name)
  end

  def set_task_list
    @task_list = TaskList.find(params[:id])
  end

end
