# frozen_string_literal: true

require 'litany/mixins'
require 'litany/resource'

module Litany
  class ECRRepository < Resource
    cfn_type 'AWS::ECR::Repository'
    parent_resource :ecr

    child_resource IAMPolicyDocument, :ecr_policy, automatic: false

    def allow(permission = :task, account: {Ref: 'AWS::AccountId'}, role: nil)
      valid_permissions = [:full, :task, :read, :read_write, :write]
      raise "Permissions must be one of the following: #{valid_permissions.inspect}. Received `#{permission.inspect}`." unless valid_permissions.include?(permission)

      actions = case permission
        when :full
          'ecr:*'
        when :task
          ['ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage']
        when :read
          ['ecr:GetAuthorizationToken', 'ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:DescribeRepositories', 'ecr:ListImages', 'ecr:DescribeImages', 'ecr:BatchGetImage']
        when :write
          ['ecr:InitiateLayerUpload', 'ecr:UploadLayerPart', 'ecr:CompleteLayerUpload', 'ecr:PutImage']
        when :read_write
          ['ecr:GetAuthorizationToken', 'ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:GetRepositoryPolicy', 'ecr:DescribeRepositories', 'ecr:ListImages', 'ecr:DescribeImages', 'ecr:BatchGetImage', 'ecr:InitiateLayerUpload', 'ecr:UploadLayerPart', 'ecr:CompleteLayerUpload', 'ecr:PutImage']
      end

      ecr_policy.next_statement do
        actions actions
        allow_principal account: account, role: role
      end
    end

    def properties
      props = {
        RepositoryName: name.tr('_', '-')
      }

      props[:RepositoryPolicyText] = ecr_policy unless ecr_policy.statements.empty?

      props
    end
  end
end
