class SessionsController < ApplicationController
  include RateLimiter

  def new
    # Redirect to admin if already logged in
    if logged_in?
      redirect_to admin? ? admin_root_path : root_path
    end
  end

  def create
    # Skip authentication if rate limited
    return if @rate_limited

    user = User.find_by(email: params[:email]&.downcase&.strip)

    if user&.authenticate(params[:password])
      # Check if user has accepted invitation
      unless user.invitation_accepted_at.present?
        flash.now[:alert] = "Your account is pending. Please use your invitation link to complete registration."
        render :new, status: :unprocessable_entity
        return
      end

      # Reset rate limit on successful login
      reset_rate_limit

      session[:user_id] = user.id
      session[:last_activity_at] = Time.current.to_s

      # Handle remember me
      if params[:remember_me] == "1"
        token = user.remember_me
        cookies.signed[:remember_token] = {
          value: token,
          expires: User::REMEMBER_TOKEN_EXPIRY.from_now,
          httponly: true,
          secure: Rails.env.production?
        }
      end

      redirect_to admin? ? admin_root_path : root_path, notice: "Welcome back, #{user.name}!"
    else
      flash.now[:alert] = "Invalid email or password."
      render :new, status: :unprocessable_entity
    end
  end

  def destroy
    current_user&.forget_me if cookies.signed[:remember_token]
    reset_session
    cookies.delete(:remember_token)
    redirect_to root_path, notice: "You have been logged out."
  end
end
