name: Build, Push and Deploy

on:
  push:
    branches:
      - main

jobs:
  build:
    name: Build and Push Docker Image
    runs-on: self-hosted

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_TOKEN }}

      - name: Build Docker Image
        run: |
          docker build -t ${{ secrets.DOCKER_USERNAME }}/ghaymah-api:${{ github.sha }} .

      - name: Push Docker Image
        run: |
          docker push ${{ secrets.DOCKER_USERNAME }}/ghaymah-api:${{ github.sha }}

  deploy-production:
    name: Deploy to Production
    needs: build
    runs-on: self-hosted

    environment:
      name: production

    steps:
      - name: Pull Latest Image
        run: |
          docker pull ${{ secrets.DOCKER_USERNAME }}/ghaymah-api:${{ github.sha }}

      - name: Stop Existing Container
        run: |
          docker stop ghaymah-api || true
          docker rm ghaymah-api || true

      - name: Run New Container
        run: |
          docker run -d \
            --name ghaymah-api \
            --restart unless-stopped \
            -p 8080:8080 \
            ${{ secrets.DOCKER_USERNAME }}/ghaymah-api:${{ github.sha }}

      - name: Verify Deployment
        run: |
          docker ps
