# frozen_string_literal: true

require 'arcana/client'
require 'litany/subsystems/arcana/arcana_secret'
require 'litany/subsystems/arcana/arcana_support'

module Litany
  class Project < Base
    child_resource ArcanaSupport, :arcana, automatic: :on_access

    # @group Secret Management

    # Returns an Arcana client for this project's combination of settings.
    # @return [Arcana::Client]
    def arcana_client
      return @arcana_client if instance_variable_defined?(:@arcana_client)
      raise 'Cannot create Arcana::Client if support is not enabled.' unless ArcanaSupport.enabled?

      @arcana_client = Arcana::Client.new(
        bucket: ArcanaSupport.instance.bucket.bucket_name,
        service_id: service_id,
        system_prefix: "litany/#{active_environment&.name}",
        aws_profile: workspace['aws.profile']
      )
    end

    # Returns a memoized ArcanaSecret instance that is a lazy representation of a string secret
    # @return [ArcanaSecret]
    def secret(material)
      @secrets ||= {}
      @secrets[material] ||= ArcanaSecret.for(self, material)
    end

    # Returns the project's service id.  Format: <stage>-<project name>-<environment>
    # @return [Symbol]
    def service_id
      parts = [
        stage,
        name,
        active_environment&.name || :unset
      ]

      parts.collect { |p| p.camel_case.downcase }.join('-').to_sym
    end

    # @endgroup
  end
end
