# frozen_string_literal: true

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

module Litany
  class ECSTaskDefinition < Resource
    cfn_type 'AWS::ECS::TaskDefinition'
    parent_resource :ecs_service

    flag :cloudwatch_logs, false
    flag :fargate, false, inherited: true

    property :command, nil, [nil, Array]
    property :container_port, 8080, 1..65_535, inherited: true
    property :entry_point, nil, [nil, Array]
    property :image, 'alpine', String
    property :memory, 100, Integer
    property :network_mode, :bridge, [:none, :bridge, :host]

    def properties
      props = {
        Family: name,
        NetworkMode: network_mode,
        TaskRoleArn: ref(ecs_service.task_role),
        ContainerDefinitions: [
          {
            Image: image,
            Memory: memory,
            Name: name,
            PortMappings: [
              {
                ContainerPort: container_port,
              }
            ]
          }
        ]
      }

      if fargate?
        props[:Cpu] = 256
        props[:Memory] = 512
        props[:NetworkMode] = :awsvpc
        props[:RequiresCompatibilities] = [:FARGATE]
        props[:ExecutionRoleArn] = ref(ecs_service.task_execution_role)
      end

      props[:ContainerDefinitions][0][:Command] = command if set_command?
      props[:ContainerDefinitions][0][:EntryPoint] = entry_point if set_entry_point?

      if cloudwatch_logs?
        props[:ContainerDefinitions][0][:LogConfiguration] = {
          LogDriver: 'awslogs',
          Options: {
            'awslogs-group': name,
            'awslogs-region': default_environment.region,
            'awslogs-stream-prefix': active_environment.name
          }
        }
      end

      props
    end
  end
end
