# frozen_string_literal: true

require "generator/config"
require "generator/file_writer"

module Generator
  module RBS
    # Generates consolidated RBS signature files for types, grouping all types for an API into a single file
    class Types
      include FileWriter

      def initialize(api_name, api_types)
        @api_name = api_name
        @api_types = api_types
      end

      def generate
        lines = [] #: Array[String]
        lines << "# #{Config::GENERATED_FILE_NOTICE}"
        lines << ""
        lines << "module Peddler"

        # Determine if this is a notification type or regular type
        is_notification = @api_name.start_with?("notifications/")
        if is_notification
          notification_name = @api_name.sub("notifications/", "").camelize
          lines << "  module Notifications"
          lines << "    module #{notification_name}"
        else
          lines << "  module Types"
          lines << "    module #{@api_name.camelize}"
        end

        # Sort types alphabetically by class name for consistent output
        sorted_types = @api_types.sort_by(&:class_name)

        # Generate each type's class definition
        sorted_types.each do |type|
          class_def = type.rbs_class_definition
          # Indent the class definition with 6 spaces (3 levels of nesting)
          indented_class = indent(class_def, 6)
          lines << indented_class
          lines << "" # Add blank line between classes
        end

        # For notifications, add module-level parse method
        if is_notification
          # Find the Notification type to get its fully qualified name
          notification_type = sorted_types.find { |t| t.class_name == "Notification" }
          if notification_type
            full_type_name = "Peddler::Notifications::#{notification_name}::Notification"
            lines << "      def self.parse: (Hash[String | Symbol, untyped]) -> #{full_type_name}"
            lines << ""
          end
        end

        # Remove trailing blank line
        lines.pop if lines.last == ""

        lines << "    end"
        lines << "  end"
        lines << "end"

        write_file(rbs_file_path, lines.join("\n") + "\n")
      end

      private

      def indent(text, spaces)
        prefix = " " * spaces
        text.lines.map { |line| line.strip.empty? ? line : "#{prefix}#{line}" }.join
      end

      def rbs_file_path
        # Determine the right path based on whether this is a notification or regular type
        if @api_name.start_with?("notifications/")
          # For notifications, remove "notifications/" prefix and put in sig/peddler/notifications/
          notification_path = @api_name.sub("notifications/", "")
          File.join(Config::BASE_PATH, "sig/peddler/notifications/#{notification_path}.rbs")
        else
          File.join(Config::BASE_PATH, "sig/peddler/types/#{@api_name}.rbs")
        end
      end
    end
  end
end
