name: Bootstrap Terraform State Resources

on:
  workflow_dispatch:
  workflow_call:
    outputs:
      s3_bucket_name:
        description: "Name of the created S3 bucket"
        value: ${{ jobs.bootstrap.outputs.s3_bucket_name }}
      dynamodb_table_name:
        description: "Name of the created DynamoDB table"
        value: ${{ jobs.bootstrap.outputs.dynamodb_table_name }}
      github_actions_role_arn:
        description: "ARN of the created GitHub Actions IAM role"
        value: ${{ jobs.bootstrap.outputs.github_actions_role_arn }}

jobs:
  bootstrap:
    runs-on: ubuntu-latest
    
    outputs:
      s3_bucket_name: ${{ steps.terraform_output.outputs.s3_bucket_name }}
      dynamodb_table_name: ${{ steps.terraform_output.outputs.dynamodb_table_name }}
      github_actions_role_arn: ${{ steps.terraform_output.outputs.github_actions_role_arn }}
    
    permissions:
      contents: read

    env:
      AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
      TF_IN_AUTOMATION: "true"
      
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.5
          terraform_wrapper: false

      # Configure AWS credentials using access keys per company policy
      # Note: Requires AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY repository secrets
      # Security: Ensure access keys follow principle of least privilege and key rotation policies
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.DATA_AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.DATA_AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ env.AWS_REGION }}

      - name: Check if resources already exist
        id: check_resources
        working-directory: infra/bootstrap
        run: |
          # Check if S3 bucket exists
          if aws s3api head-bucket --bucket "aimodelshare-tfstate-prod-copilot-2024" 2>/dev/null; then
            echo "s3_exists=true" >> $GITHUB_OUTPUT
          else
            echo "s3_exists=false" >> $GITHUB_OUTPUT
          fi
          
          # Check if DynamoDB table exists
          if aws dynamodb describe-table --table-name "aimodelshare-tf-locks" 2>/dev/null; then
            echo "dynamodb_exists=true" >> $GITHUB_OUTPUT
          else
            echo "dynamodb_exists=false" >> $GITHUB_OUTPUT
          fi

          # Check if GitHub OIDC provider exists
          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
          if aws iam get-open-id-connect-provider --open-id-connect-provider-arn "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" 2>/dev/null; then
            echo "oidc_provider_exists=true" >> $GITHUB_OUTPUT
          else
            echo "oidc_provider_exists=false" >> $GITHUB_OUTPUT
          fi

          # Check if GitHub Actions IAM role exists
          if aws iam get-role --role-name "aimodelshare-github-oidc-deployer" 2>/dev/null; then
            echo "github_role_exists=true" >> $GITHUB_OUTPUT
          else
            echo "github_role_exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Terraform Init
        working-directory: infra/bootstrap
        run: terraform init -input=false

      - name: Terraform Validate
        working-directory: infra/bootstrap
        run: terraform validate

      - name: Import existing resources (if they exist)
        working-directory: infra/bootstrap
        if: steps.check_resources.outputs.s3_exists == 'true' || steps.check_resources.outputs.dynamodb_exists == 'true' || steps.check_resources.outputs.oidc_provider_exists == 'true' || steps.check_resources.outputs.github_role_exists == 'true'
        run: |
          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
          
          if [ "${{ steps.check_resources.outputs.s3_exists }}" = "true" ]; then
            echo "Importing existing S3 bucket..."
            terraform import aws_s3_bucket.terraform_state aimodelshare-tfstate-prod-copilot-2024 || true
            terraform import aws_s3_bucket_versioning.terraform_state aimodelshare-tfstate-prod-copilot-2024 || true
            terraform import aws_s3_bucket_server_side_encryption_configuration.terraform_state aimodelshare-tfstate-prod-copilot-2024 || true
            terraform import aws_s3_bucket_public_access_block.terraform_state aimodelshare-tfstate-prod-copilot-2024 || true
          fi
          
          if [ "${{ steps.check_resources.outputs.dynamodb_exists }}" = "true" ]; then
            echo "Importing existing DynamoDB table..."
            terraform import aws_dynamodb_table.terraform_locks aimodelshare-tf-locks || true
          fi

          if [ "${{ steps.check_resources.outputs.oidc_provider_exists }}" = "true" ]; then
            echo "Importing existing GitHub OIDC provider..."
            terraform import aws_iam_openid_connect_provider.github "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" || true
          fi

          if [ "${{ steps.check_resources.outputs.github_role_exists }}" = "true" ]; then
            echo "Importing existing GitHub Actions IAM role..."
            terraform import aws_iam_role.github_actions aimodelshare-github-oidc-deployer || true
            # Also try to import the policy and attachment if they exist
            terraform import aws_iam_policy.github_actions_deployment "arn:aws:iam::${ACCOUNT_ID}:policy/aimodelshare-github-actions-deployment" || true
            terraform import aws_iam_role_policy_attachment.github_actions_deployment aimodelshare-github-oidc-deployer/arn:aws:iam::${ACCOUNT_ID}:policy/aimodelshare-github-actions-deployment || true
          fi

      - name: Terraform Plan
        id: plan
        working-directory: infra/bootstrap
        run: |
          terraform plan -input=false -out=tfplan
          
      - name: Terraform Apply
        working-directory: infra/bootstrap
        run: terraform apply -input=false -auto-approve tfplan

      - name: Get Terraform Outputs
        id: terraform_output
        working-directory: infra/bootstrap
        run: |
          S3_BUCKET=$(terraform output -raw s3_bucket_name)
          DYNAMODB_TABLE=$(terraform output -raw dynamodb_table_name)
          GITHUB_ROLE_ARN=$(terraform output -raw github_actions_role_arn)
          echo "s3_bucket_name=$S3_BUCKET" >> $GITHUB_OUTPUT
          echo "dynamodb_table_name=$DYNAMODB_TABLE" >> $GITHUB_OUTPUT
          echo "github_actions_role_arn=$GITHUB_ROLE_ARN" >> $GITHUB_OUTPUT
          echo "✅ Bootstrap completed successfully!"
          echo "  S3 Bucket: $S3_BUCKET"
          echo "  DynamoDB Table: $DYNAMODB_TABLE"
          echo "  GitHub Actions Role ARN: $GITHUB_ROLE_ARN"
