class CoffeeBagsController < ApplicationController
  before_action :require_authentication
  before_action :check_premium!
  before_action :set_roaster
  before_action :set_coffee_bag, only: %i[edit update duplicate destroy remove_image archive restore]
  before_action :load_coffee_bags, only: %i[index search]
  before_action :load_roasters, only: %i[edit update duplicate]

  def index; end

  def search
    render :index
  end

  def new
    @coffee_bag = @roaster.coffee_bags.build
  end

  def edit; end

  def create
    @coffee_bag = @roaster.coffee_bags.build(coffee_bag_params)
    if @coffee_bag.save
      redirect_to roaster_coffee_bags_path(@roaster, format: :html), notice: "#{@coffee_bag.display_name} was created."
    else
      render :new, status: :unprocessable_content
    end
  end

  def update
    if @coffee_bag.update(coffee_bag_params)
      redirect_to roaster_coffee_bags_path(@coffee_bag.roaster, format: :html), notice: "#{@coffee_bag.display_name} was updated."
    else
      render :edit, status: :unprocessable_content
    end
  end

  def duplicate
    if params[:roast_date].blank?
      flash.now[:alert] = "Please provide a roast date to duplicate this coffee bag."
      render :edit, status: :unprocessable_content
    else
      duplicate = @coffee_bag.duplicate(params[:roast_date])
      if duplicate.save
        redirect_to roaster_coffee_bags_path(@roaster, format: :html), notice: "#{@coffee_bag.display_name} was duplicated as #{duplicate.display_name}."
      else
        flash.now[:alert] = "Failed to duplicate coffee bag."
        render :edit, status: :unprocessable_content
      end
    end
  end

  def destroy
    @coffee_bag.destroy!
    redirect_to roaster_coffee_bags_path(@roaster, format: :html), notice: "#{@coffee_bag.display_name} was deleted."
  end

  def remove_image
    @coffee_bag.image.purge
    render turbo_stream: turbo_stream.remove("coffee-bag-image")
  end

  def scrape_info
    Rails.logger.info "Scraping coffee bag info for #{params[:url]} by #{Current.user.id}"
    info = CoffeeBagScraper.new.get_info(params[:url])

    if info && info[:error].blank?
      render json: info
    else
      error = info[:error].presence || "Could not extract information from URL"
      render json: {error:}, status: :unprocessable_content
    end
  end

  def archive
    @coffee_bag.update(archived_at: Time.current)
    redirect_to roaster_coffee_bags_path(@roaster, format: :html), notice: "#{@coffee_bag.display_name} was archived."
  end

  def restore
    @coffee_bag.update(archived_at: nil)
    redirect_to roaster_coffee_bags_path(@roaster, format: :html), notice: "#{@coffee_bag.display_name} was restored."
  end

  private

  def set_roaster
    @roaster = Current.user.roasters.find(params[:roaster_id])
  rescue ActiveRecord::RecordNotFound
    redirect_to roasters_path, alert: "Roaster not found"
  end

  def set_coffee_bag
    @coffee_bag = @roaster.coffee_bags.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to roaster_coffee_bags_path(@roaster), alert: "Coffee bag not found"
  end

  def load_coffee_bags
    @coffee_bags = @roaster.coffee_bags.active_first.by_roast_date
    @coffee_bags = @coffee_bags.where("coffee_bags.name ILIKE ?", "%#{ActiveRecord::Base.sanitize_sql_like(params[:coffee])}%") if params[:coffee].present?
  end

  def load_roasters
    @roasters = Current.user.roasters.order_by_name.includes(:coffee_bags)
  end

  def coffee_bag_params
    cb_params = params.expect(coffee_bag: %i[name url roaster_id canonical_coffee_bag_id roast_date image] + CoffeeBag::DISPLAY_ATTRIBUTES)
    roaster = Current.user.roasters.find_by(id: cb_params[:roaster_id])
    cb_params[:roaster_id] = @roaster.id if roaster.blank?
    cb_params
  end
end
