name: Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      environment:
        description: 'Environment to deploy to'
        required: true
        default: 'production'
        type: choice
        options:
          - production
          - staging

env:
  NODE_VERSION: '18.x'

jobs:
  # Deploy to Vercel
  deploy-vercel:
    name: Deploy to Vercel
    runs-on: ubuntu-latest
    if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'production')
    
    environment:
      name: production
      url: ${{ steps.deploy.outputs.url }}
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🏗️ Build application
        run: npm run build
        env:
          NEXT_PUBLIC_APP_ENV: production
          NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}
          NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}

      - name: 🚀 Deploy to Vercel
        id: deploy
        uses: vercel/action@v1
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: '--prod'

      - name: 📝 Comment on PR
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v6
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '🚀 Deployed to Vercel: ${{ steps.deploy.outputs.url }}'
            })

  # Deploy to Netlify (alternative)
  deploy-netlify:
    name: Deploy to Netlify
    runs-on: ubuntu-latest
    if: false # Enable by changing to true and configuring secrets
    
    environment:
      name: production
      url: ${{ steps.deploy.outputs.deploy-url }}
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🏗️ Build application
        run: npm run build

      - name: 🚀 Deploy to Netlify
        id: deploy
        uses: netlify/actions/deploy@master
        with:
          publish-dir: './out'
          production-branch: main
          production-deploy: true
          netlify-config-path: ./netlify.toml
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}

  # Deploy Docker Container (for API/Backend)
  deploy-docker:
    name: Deploy Docker Container
    runs-on: ubuntu-latest
    if: false # Enable for containerized apps
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🐳 Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

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

      - name: 📝 Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKER_USERNAME }}/app
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=sha,prefix={{branch}}-

      - name: 🏗️ Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  # Deploy to AWS (S3 + CloudFront)
  deploy-aws:
    name: Deploy to AWS
    runs-on: ubuntu-latest
    if: false # Enable for AWS deployment
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🏗️ Build application
        run: npm run build

      - name: 🔧 Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - name: 📤 Deploy to S3
        run: |
          aws s3 sync ./out s3://${{ secrets.S3_BUCKET_NAME }} --delete

      - name: 🔄 Invalidate CloudFront
        run: |
          aws cloudfront create-invalidation \
            --distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }} \
            --paths "/*"

  # Post-deployment checks
  smoke-test:
    name: Smoke Tests
    runs-on: ubuntu-latest
    needs: [deploy-vercel]
    if: success()
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🧪 Run smoke tests
        run: |
          echo "Running smoke tests..."
          curl -f ${{ needs.deploy-vercel.outputs.url }} || exit 1
          echo "✅ Site is accessible"

      - name: 🔍 Check critical endpoints
        run: |
          # Add your critical endpoint checks here
          echo "Checking /api/health..."
          curl -f ${{ needs.deploy-vercel.outputs.url }}/api/health || echo "Health check endpoint not found"

  # Notify deployment
  notify:
    name: Notify Deployment
    runs-on: ubuntu-latest
    needs: [deploy-vercel, smoke-test]
    if: always()
    
    steps:
      - name: 📢 Send Slack notification
        if: false # Enable if using Slack
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {
              "text": "Deployment ${{ needs.deploy-vercel.result }}",
              "blocks": [
                {
                  "type": "section",
                  "text": {
                    "type": "mrkdwn",
                    "text": "*Deployment Status:* ${{ needs.deploy-vercel.result == 'success' && '✅ Success' || '❌ Failed' }}\n*Branch:* ${{ github.ref_name }}\n*Commit:* ${{ github.sha }}"
                  }
                }
              ]
            }
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}