version: 2.1
orbs:
    aws-cli: circleci/aws-cli@4.1.2
    aws-ecr: circleci/aws-ecr@9.4.0
    aws-ecs: circleci/aws-ecs@4.0.0
jobs:
    build_and_test:
        docker:
            - image: circleci/node:14
        working_directory: ~/app
        steps:
            - checkout
            - run:
                  name: Install Frontend Dependencies
                  command: |
                      npm install
            - run:
                  name: Install Backend Dependencies
                  command: |
                      cd backend
                      npm install
            - run:
                  name: Build Frontend
                  command: |
                      npm run build
            - run:
                  name: Test Frontend
                  command: |
                      npm test
    run_task:
        docker:
            - image: cimg/python:3.10
        steps:
            - aws-cli/setup:
                    role_arn: arn:aws:iam::982081055194:role/circleci-ecs-ecr
                    role_session_name: example-session
            - aws-ecs/run_task:
                    awsvpc: true
                    assign_public_ip: ENABLED
                    cluster: arn:aws:ecs:eu-north-1:982081055194:cluster/mern-ludo-cluster
                    launch_type: FARGATE
                    task_definition: mern-ludo-fargate
                    subnet_ids: subnet-06f63f5063b74a7c9,subnet-07cdbe8b01b46e0b7,subnet-06dbac60591c79f5d
                    security_group_ids: sg-0cfd2369802b8be43

workflows:
    build_and_test_and_deploy:
        jobs:
            - build_and_test
            - aws-ecr/build_and_push_image:
                  auth:
                      - aws-cli/setup:
                            role_arn: arn:aws:iam::982081055194:role/circleci-ecs-ecr
                            role_session_name: ecr-session
                  repo: mern-ludo
                  public_registry: true
                  requires:
                      - build_and_test
                  filters:
                      branches:
                          only:
                              - main
            - run_task:
                  requires:
                      - aws-ecr/build_and_push_image
                  filters:
                      branches:
                          only:
                              - main