class Api::V1::MoviesController < ApplicationController
  before_action :authenticate_user!, only: [:create, :update, :destroy]

  before_action :set_movies
  before_action :set_movie, only: [:show, :update, :destroy]

  def index; end
  def show;  end

  def create
    @movie = Movie.new(movie_params)

    unless @movie.save
      render json: {movie: {errors: @movie.errors}}, status: :unprocessable_entity
    end
  end

  def update
    unless @movie.update(movie_params)
      render json: {movie: {errors: @movie.errors}}, status: :unprocessable_entity
    end
  end

  def destroy
    if @movie.destroy
      render json: {}, status: :ok
    else
      render json: {movie: {errors: @movie.errors}}, status: :unprocessable_entity
    end
  end

  private

    def movie_params
      params.require(:movie).permit(
        :title, :release_year,
        casting_attributes:   [:id, :first_name, :last_name, :email, :password],
        directors_attributes: [:id, :first_name, :last_name, :email, :password],
        producers_attributes: [:id, :first_name, :last_name, :email, :password]
      )
    end

    def set_movie
      @movie = @movies.find_by(id: (params[:id] || params[:user_id]))

      unless @movie
        render json: {movie: []}, status: :not_found
      end
    end

    def set_movies
      @movies = Movie.eager_load(:casting, :directors, :producers).order(created_at: :desc)
    end
end
