# frozen_string_literal: true

# app/controllers/features_controller.rb
class FeaturesController < ApplicationController
  before_action :authenticate_user!
  before_action :ensure_admin

  def index
    all_features = Flipper.features.map(&:name)

    gon.organizations = Organization.all.order(:name).map do |org|
      enabled_features = all_features.select { |f| Flipper.enabled?(f, org) }.map { |f| { name: f } }
      org.as_json.merge(enabled_features:)
    end

    gon.features = all_features.map { |f| { name: f } }.compact
  end

  # Adds a new feature to Flipper.
  def add_feature
    feature_name = params[:feature_name]&.strip

    if feature_name.blank?
      render json: { error: "Feature name cannot be blank" }, status: :unprocessable_entity
      return
    end

    unless feature_name.match?(/\A[a-zA-Z][a-zA-Z0-9_]*\z/)
      render json: { error: "Feature name must start with a letter and contain only letters, numbers, and underscores" },
             status: :unprocessable_entity
      return
    end

    Flipper.add(feature_name.to_sym)

    render json: {
      status: 200,
      message: "Feature '#{feature_name}' created successfully",
      feature_name:
    }
  rescue StandardError => e
    render json: { error: "Failed to create feature: #{e.message}" }, status: :unprocessable_entity
  end

  def remove_feature
    feature_name = params[:id]

    if feature_name.blank?
      render json: { error: "Feature name cannot be blank." }, status: :bad_request
      return
    end

    begin
      Flipper.remove(feature_name)
      head :no_content # or render a success message
    rescue StandardError => e
      render json: { error: "Failed to remove feature: #{e.message}" }, status: :unprocessable_entity
    end
  end

  def show
    organization = Organization.find(params[:id])
    actor = organization

    features_with_states = Flipper.features.map do |feature|
      {
        name: feature.name,
        enabled: Flipper.enabled?(feature.name, actor)
      }
    end

    render json: features_with_states.compact
  rescue ActiveRecord::RecordNotFound
    render json: { error: "Organization not found" }, status: :not_found
  rescue StandardError => e
    render json: { error: e.message }, status: :unprocessable_entity
  end

  # Toggles a feature for a specific organization.
  def toggle_feature
    feature_name = params[:id]
    organization = Organization.find(params[:organization_id])
    actor = organization
    state = ActiveModel::Type::Boolean.new.cast(params[:state])
    feature = Flipper[feature_name]

    if state
      feature.enable(actor)
    else
      feature.disable(actor)
    end

    render json: {
      status: 200,
      message: "Feature '#{feature_name}' successfully #{state ? 'enabled' : 'disabled'} for #{organization.name}"
    }
  rescue ActiveRecord::RecordNotFound
    render json: { error: "Organization or Feature not found" }, status: :not_found
  rescue StandardError => e
    render json: { error: e.message }, status: :unprocessable_entity
  end

  private

  def ensure_admin
    redirect_to root_path, alert: "Access denied" unless current_user&.admin?
  end
end
