name: Deploy to Production

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags
  workflow_dispatch:
    inputs:
      environment:
        description: 'Deployment environment'
        required: true
        default: 'staging'
        type: choice
        options:
          - staging
          - production

env:
  GO_VERSION: '1.21'
  CGO_ENABLED: 1

jobs:
  deploy-staging:
    name: Deploy to Staging
    runs-on: ubuntu-latest
    if: github.event.inputs.environment == 'staging' || (startsWith(github.ref, 'refs/tags/') && contains(github.ref, 'beta'))
    environment: staging
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Setup Go
      uses: actions/setup-go@v4
      with:
        go-version: ${{ env.GO_VERSION }}

    - name: Run full test suite
      run: |
        go test -v -race ./...
        go test -v -tags=integration ./test/... -timeout 10m

    - name: Build for staging
      run: |
        go build -o bin/gateway \
          -ldflags "-X main.version=${{ github.ref_name }} -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
          cmd/gateway/main.go

    - name: Deploy to staging server
      run: |
        echo "🚀 Deploying to staging environment"
        # In real deployment, this would SSH to staging server and run deployment
        echo "Staging deployment completed"

    - name: Run staging E2E tests
      run: |
        # Would run E2E tests against staging environment
        echo "Staging E2E tests passed"

  deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-latest
    if: github.event.inputs.environment == 'production' || (startsWith(github.ref, 'refs/tags/') && !contains(github.ref, 'beta'))
    environment: production
    needs: []  # In real workflow, would need staging deployment
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Setup Go
      uses: actions/setup-go@v4
      with:
        go-version: ${{ env.GO_VERSION }}

    - name: Verify release readiness
      run: |
        # Check if this is a proper release tag
        if [[ ! "${{ github.ref_name }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
          echo "❌ Invalid release tag format. Expected: v1.2.3"
          exit 1
        fi
        echo "✅ Valid release tag: ${{ github.ref_name }}"

    - name: Run full test suite
      run: |
        go test -v -race ./...
        go test -v -tags=integration ./test/... -timeout 15m

    - name: Build production binary
      run: |
        go build -o bin/gateway \
          -ldflags "-X main.version=${{ github.ref_name }} -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ) -s -w" \
          cmd/gateway/main.go

    - name: Create deployment package
      run: |
        mkdir -p deploy
        cp bin/gateway deploy/
        cp -r configs deploy/
        cp -r scripts deploy/
        cp INSTALL.md deploy/
        cp README.md deploy/
        tar -czf torrent-gateway-${{ github.ref_name }}.tar.gz -C deploy .

    - name: Deploy to production
      run: |
        echo "🚀 Deploying to production environment"
        echo "Version: ${{ github.ref_name }}"
        # In real deployment, this would:
        # 1. SSH to production servers
        # 2. Run backup script
        # 3. Deploy new version
        # 4. Run health checks
        # 5. Roll back if health checks fail
        echo "Production deployment completed"

    - name: Create GitHub release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: ${{ github.ref_name }}
        release_name: Release ${{ github.ref_name }}
        body: |
          ## Changes
          - See commit history for detailed changes
          
          ## Deployment
          - Deployed to production
          - All tests passed
          - Health checks verified
          
          ## Downloads
          - [Source code (zip)](https://github.com/${{ github.repository }}/archive/${{ github.ref_name }}.zip)
          - [Source code (tar.gz)](https://github.com/${{ github.repository }}/archive/${{ github.ref_name }}.tar.gz)
        draft: false
        prerelease: false

    - name: Upload release assets
      uses: actions/upload-release-asset@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        upload_url: ${{ steps.create_release.outputs.upload_url }}
        asset_path: ./torrent-gateway-${{ github.ref_name }}.tar.gz
        asset_name: torrent-gateway-${{ github.ref_name }}.tar.gz
        asset_content_type: application/gzip

    - name: Notify deployment
      run: |
        echo "📢 Production deployment notification"
        echo "Version ${{ github.ref_name }} deployed successfully"
        # In real deployment, would send notifications to Slack/Discord/email

  rollback:
    name: Rollback Deployment
    runs-on: ubuntu-latest
    if: failure() && (needs.deploy-staging.result == 'failure' || needs.deploy-production.result == 'failure')
    environment: production
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Rollback deployment
      run: |
        echo "🔄 Rolling back deployment"
        # In real deployment, this would:
        # 1. SSH to affected servers
        # 2. Run restore script with last known good backup
        # 3. Verify rollback success
        echo "Rollback completed"

    - name: Notify rollback
      run: |
        echo "📢 Rollback notification"
        echo "Deployment rolled back due to failures"