class RequestsController < ApplicationController
  def new
    @entry = Entry.new

    if current_user
      @pending_count = current_user.requested_entries.where(status: [ :requested, :approved ]).count
    elsif params[:email].present?
      @pending_count = User.find_by(email: params[:email])&.requested_entries&.where(status: [ :requested, :approved ])&.count || 0
    else
      @pending_count = 0
    end
  end

  def create
    # If user is logged in, use their account
    if current_user
      @user = current_user
    else
      # Anonymous submission - need to find or create user
      email = request_params[:email]
      existing_user = User.find_by(email: email)

      # Check if user has already accepted an invitation
      if existing_user&.invitation_accepted_at.present?
        redirect_to login_path, alert: "An account with this email already exists. Please log in."
        return
      end

      # Use existing pending user or create new one
      @user = existing_user || User.new(
        name: request_params[:name],
        email: email,
        password: SecureRandom.alphanumeric(32),
        role: :contributor
      )
    end

    # Create entry in a transaction
    ActiveRecord::Base.transaction do
      # Save user only if it's a new record
      if @user.new_record? && !@user.save
        @pending_count = 0
        @entry = Entry.new(entry_params)
        flash.now[:alert] = "There was an error submitting your request. Please check the form."
        render :new, status: :unprocessable_entity
        raise ActiveRecord::Rollback
        return
      end

      # Create entry
      @entry = Entry.new(entry_params)
      @entry.status = :requested
      @entry.requested_by = @user

      if @entry.save
        redirect_to root_path, notice: "Thank you for your request! We'll review it and get back to you soon."
      else
        @pending_count = 0
        flash.now[:alert] = "There was an error submitting your request. Please check the form."
        render :new, status: :unprocessable_entity
        raise ActiveRecord::Rollback
      end
    end
  end

  private

  def request_params
    params.require(:entry).permit(:name, :email, :category, :fi, :en, :sv, :no, :ru, :de, :notes)
  end

  def entry_params
    request_params.except(:name, :email)
  end
end
