name: Telegram Mini App Shop Builder

on:
  push:
    branches:
      - master
      - 'issue/**'
      - develop
  pull_request:
    types:
      - opened
      - synchronize
      - reopened

permissions:
  contents: write

jobs:
  test_frontend:
    name: Run Frontend tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v6

      - name: Install dependencies
        working-directory: frontend/spa
        run: npm install

      - name: Run tests
        working-directory: frontend/spa
        env:
          APP_ENV: testing
        run: npm run test

  test_backend:
    name: Run Backend tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup PHP 7.4
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.4'
          tools: composer
          extensions: mbstring

      - name: Install Composer dependencies
        working-directory: module/oc_telegram_shop/upload/oc_telegram_shop
        run: composer install --no-progress --no-interaction

      - name: Run tests
        working-directory: module/oc_telegram_shop/upload/oc_telegram_shop
        env:
          APP_ENV: testing
        run: ./vendor/bin/phpunit --testdox tests/Unit tests/Telegram

  phpcs:
    name: Run PHP_CodeSniffer
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup PHP 7.4
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.4'
          tools: phpcs

      - name: Run PHP_CodeSniffer
        working-directory: module/oc_telegram_shop/upload/oc_telegram_shop
        run: phpcs --standard=PSR12 bastion framework src

  module-build:
    name: Build module.
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v6

      - name: Setup PHP 7.4
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.4'
          tools: composer

      - name: Build module
        run: |
          bash scripts/ci/build.sh "${GITHUB_WORKSPACE}"

      - name: Upload build artifact
        uses: actions/upload-artifact@v4
        with:
          name: oc_telegram_shop.ocmod.zip
          path: ./build/oc_telegram_shop.ocmod.zip
          retention-days: 1

  release:
    runs-on: ubuntu-latest
    needs: [ test_frontend, test_backend, module-build ]
    if: github.ref == 'refs/heads/master'
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # to fetch tags

      - name: Extract tag and set filename
        id: meta
        run: |
          # Проверяем, указывает ли HEAD на тег (релиз)
          RELEASE_TAG=$(git tag --points-at HEAD | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
          
          if [ -n "$RELEASE_TAG" ]; then
            echo "Это полноценный релиз"
            TAG="$RELEASE_TAG"
            FILENAME="oc_telegram_shop_${TAG}.ocmod.zip"
            IS_RELEASE=true
          else
            echo "Это dev-сборка"
            LAST_TAG=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
            [ -z "$LAST_TAG" ] && LAST_TAG="v0.0.0"
            SHORT_SHA=$(git rev-parse --short=7 HEAD)
            DATE=$(date +%Y%m%d%H%M)
            TAG="${LAST_TAG}-dev.${DATE}+${SHORT_SHA}"
            FILENAME="oc_telegram_shop_${TAG}.ocmod.zip"
            IS_RELEASE=false
          fi

          echo "is_release=$IS_RELEASE" >> $GITHUB_OUTPUT
          echo "tag=$TAG" >> $GITHUB_OUTPUT
          echo "filename=$FILENAME" >> $GITHUB_OUTPUT

      - name: Download build artifact
        uses: actions/download-artifact@v4
        with:
          name: oc_telegram_shop.ocmod.zip
          path: ./build

      - name: Rename artifact file
        run: mv ./build/oc_telegram_shop.ocmod.zip ./build/${{ steps.meta.outputs.filename }}

      - name: Delete existing GitHub release and tag
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG=${{ steps.meta.outputs.tag }}
          echo "⛔ Deleting existing release and tag (if any): $TAG"
          gh release delete "$TAG" --cleanup-tag --yes || true
          git push origin ":refs/tags/$TAG" || true

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          draft: ${{ steps.meta.outputs.is_release == 'false' }}
          tag_name: ${{ steps.meta.outputs.tag }}
          files: ./build/${{ steps.meta.outputs.filename }}
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Delete draft releases older than 7 days
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const daysToKeep = 7;
            const cutoffDate = new Date(Date.now() - daysToKeep * 24 * 60 * 60 * 1000);
            
            const releases = await github.rest.repos.listReleases({
              owner: context.repo.owner,
              repo: context.repo.repo,
              per_page: 100
            });
            
            for (const release of releases.data) {
              if (release.draft) {
                const created = new Date(release.created_at);
                if (created < cutoffDate) {
                  console.log(`Deleting draft release: ${release.name || release.tag_name} (${release.id})`);
                  await github.rest.repos.deleteRelease({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    release_id: release.id
                  });
            
                  try {
                    await github.rest.git.deleteRef({
                      owner: context.repo.owner,
                      repo: context.repo.repo,
                      ref: `tags/${release.tag_name}`
                    });
                    console.log(`Deleted tag: ${release.tag_name}`);
                  } catch (err) {
                    console.log(`Tag ${release.tag_name} not found or already deleted.`);
                  }
                }
              }
            }
