namespace :users do
  desc "Reset password for a user"
  task reset_password: :environment do
    email = ENV['EMAIL']
    new_password = ENV['PASSWORD']

    if email.blank?
      puts "Usage: EMAIL=user@example.com PASSWORD=newpassword rails users:reset_password"
      exit 1
    end

    user = User.find_by(email_address: email)
    if user.nil?
      puts "Error: User with email '#{email}' not found."
      exit 1
    end

    if new_password.blank?
      puts "Error: PASSWORD environment variable is required."
      exit 1
    end

    if user.password_digest.blank?
      puts "Warning: User appears to be an OIDC user (no password set)."
      print "Do you want to set a local password for this OIDC user? (y/N): "
      response = STDIN.gets.chomp.downcase
      unless response == 'y' || response == 'yes'
        puts "Password reset cancelled."
        exit 0
      end
    end

    user.password = new_password
    user.password_confirmation = new_password

    if user.save
      # Destroy all sessions to force re-login
      user.sessions.destroy_all

      puts "✅ Password successfully updated for #{user.email_address}"
      puts "   User: #{user.email_address} (#{user.role})"
      puts "   All existing sessions have been terminated."
      puts "   User will need to log in with the new password."
    else
      puts "❌ Failed to update password:"
      user.errors.full_messages.each { |msg| puts "   - #{msg}" }
      exit 1
    end
  end

  desc "List all users"
  task list: :environment do
    users = User.order(:role, :email_address)

    puts "Users (#{users.count}):"
    puts "=" * 60
    users.each do |user|
      has_password = user.password_digest.present? ? "local" : "OIDC"
      last_login = user.sessions.maximum(:created_at)

      puts "📧 #{user.email_address}"
      puts "   Role: #{user.role} | Auth: #{has_password}"
      puts "   Last login: #{last_login ? last_login.strftime('%Y-%m-%d %H:%M') : 'Never'}"
      puts "   Active sessions: #{user.sessions.count}"
      puts
    end
  end

  desc "Create admin user (only if no users exist)"
  task create_admin: :environment do
    if User.any?
      puts "❌ Users already exist. Admin creation is disabled."
      puts "   Use 'rails users:reset_password' to reset an existing user's password."
      exit 1
    end

    email = ENV['EMAIL']
    password = ENV['PASSWORD']

    if email.blank? || password.blank?
      puts "Usage: EMAIL=admin@example.com PASSWORD=securepassword rails users:create_admin"
      exit 1
    end

    user = User.new(
      email_address: email,
      password: password,
      password_confirmation: password
    )

    if user.save
      puts "✅ Admin user created successfully:"
      puts "   Email: #{user.email_address}"
      puts "   Role: #{user.role}"
      puts "   You can now log in to the application."
    else
      puts "❌ Failed to create admin user:"
      user.errors.full_messages.each { |msg| puts "   - #{msg}" }
      exit 1
    end
  end
end