name: deploy

on:
  push:
    branches:
      - main
  workflow_dispatch:

permissions:
  contents: read

jobs:
  deploy:
    if: github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'

      - run: dotnet restore KArtSell.sln

      - run: dotnet build KArtSell.sln --no-restore -c Release

      - name: Publish Release Build
        run: |
          dotnet publish -c Release -o ./publish src/KArtSell.Host
          dotnet publish -c Release -o ./publish src/KArtSell.DbMigrator

      - name: Create deployment package
        run: |
          cd ./publish
          zip -r ../kartsell-release.zip .
          cd ..
          ls -lh kartsell-release.zip

      - name: Deploy via SCP to server
        env:
          DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
        run: |
          # SSH 키 설정 (SSH_KEY에서 변환)
          echo "$DEPLOY_KEY" > /tmp/deploy_key.pem
          chmod 600 /tmp/deploy_key.pem

          # 서버에 파일 전송
          echo "📦 Deploying kartsell-release.zip to server..."
          scp -i /tmp/deploy_key.pem -o StrictHostKeyChecking=no \
            ./kartsell-release.zip kjh2064@178.104.200.7:/tmp/

          echo "✅ File transferred"
          echo ""
          echo "📋 Next steps on server (run these):"
          echo "  ssh kjh2064@178.104.200.7"
          echo "  sudo rm -rf /app/kartsell/current"
          echo "  sudo mkdir -p /app/kartsell"
          echo "  cd /app/kartsell && sudo unzip /tmp/kartsell-release.zip"
          echo "  export KARTSELL_POSTGRES='${{ secrets.KARTSELL_POSTGRES }}'"
          echo "  dotnet KArtSell.DbMigrator.dll"
          echo "  sudo systemctl restart kartsell"
          echo ""
          echo "✅ Deployment package ready"

          # Cleanup
          rm /tmp/deploy_key.pem

  notify:
    if: always()
    needs: deploy
    runs-on: ubuntu-latest
    steps:
      - name: Notify deployment status
        env:
          TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
          TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
        run: |
          STATUS="${{ needs.deploy.result }}"
          if [ "$STATUS" = "success" ]; then
            MESSAGE="✅ K-ArtSell Aegis deployed successfully to production"
          else
            MESSAGE="❌ K-ArtSell Aegis deployment failed"
          fi

          curl -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" \
            -d "chat_id=$TELEGRAM_CHAT_ID" \
            -d "text=$MESSAGE" \
            -d "parse_mode=HTML" || echo "Telegram notification failed"
