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

  def create
    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

      session[:user_id] = user.id
      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
    session[:user_id] = nil
    redirect_to root_path, notice: "You have been logged out."
  end
end
