name: Update database types

on:
  push:
    branches:
      - main
    paths:
      - supabase/migrations/*.sql
  workflow_dispatch:

jobs:
  update:
    runs-on: ubuntu-latest

    env:
      SUPABASE_ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
      PROJECT_REF: ${{ secrets.SUPABASE_PROJECT_ID }}
      DB_PASSWORD: ${{ secrets.SUPABASE_DB_PASSWORD }}

    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: supabase/setup-cli@v1
        with:
          version: latest

      - name: Generate database types
        run: |
          supabase gen types typescript --local > supabase/functions/_shared/database.types.ts

      - name: Check for changes
        id: git_status
        run: |
          if [[ -n "$(git status --porcelain)" ]]; then
            echo "changed=true" >> $GITEA_OUTPUT
          else
            echo "changed=false" >> $GITEA_OUTPUT
          fi

      - name: Commit changes
        if: steps.git_status.outputs.changed == 'true'
        run: |
          git config user.name "supabot"
          git config user.email "supabot@example.com"
          git add supabase/functions/_shared/database.types.ts
          git commit -m "chore: update database types"

      - name: Push changes
        if: steps.git_status.outputs.changed == 'true'
        run: |
          git push