name: Deploy

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Get full git history for checking file changes

      - name: Get previous tag
        id: previoustag
        if: github.event_name == 'push'
        run: |
          echo "tag=$(git describe --tags --abbrev=0 HEAD^)" >> $GITHUB_OUTPUT
        continue-on-error: true

      - name: Setup pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 9

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'pnpm'

      - name: Install Dependencies
        run: pnpm install --frozen-lockfile

      - name: Run deploy script
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          PROJECT_NAME: ${{ secrets.PROJECT_NAME }}
          DATABASE_NAME: ${{ secrets.DATABASE_NAME }}
          DATABASE_ID: ${{ secrets.DATABASE_ID }}
          KV_NAMESPACE_NAME: ${{ secrets.KV_NAMESPACE_NAME }}
          KV_NAMESPACE_ID: ${{ secrets.KV_NAMESPACE_ID }}
          CUSTOM_DOMAIN: ${{ secrets.CUSTOM_DOMAIN }}
          AUTH_GITHUB_ID: ${{ secrets.AUTH_GITHUB_ID }}
          AUTH_GITHUB_SECRET: ${{ secrets.AUTH_GITHUB_SECRET }}
          AUTH_GOOGLE_ID: ${{ secrets.AUTH_GOOGLE_ID }}
          AUTH_GOOGLE_SECRET: ${{ secrets.AUTH_GOOGLE_SECRET }}
          AUTH_SECRET: ${{ secrets.AUTH_SECRET }}
        run: pnpm dlx tsx scripts/deploy/index.ts

      # Clean up
      - name: Post deployment cleanup
        run: |
          rm -f .env*.*
          rm -f wrangler*.json