name: Build Windows Installer

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  build-windows:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable

      - name: Get dependencies
        run: flutter pub get

      - name: Build Windows release
        run: flutter build windows --release

      - name: Install Inno Setup
        run: |
          choco install innosetup --no-progress -y

      - name: Sync version from pubspec.yaml
        shell: pwsh
        run: |
          $version = (Select-String -Path pubspec.yaml -Pattern '^version:\s*([0-9]+\.[0-9]+\.[0-9]+)').Matches[0].Groups[1].Value
          (Get-Content windows/installer.iss -Raw) -replace '#define MyAppVersion "[^"]+"', "#define MyAppVersion `"$version`"" | Set-Content windows/installer.iss
          Write-Host "Inno Setup version: $version"

      - name: Build Inno Setup installer
        shell: cmd
        run: |
          "C:\ProgramData\chocolatey\bin\ISCC.exe" windows\installer.iss

      - name: Upload release artifacts
        uses: actions/upload-artifact@v4
        with:
          name: imajViewer-windows
          path: |
            build/windows/x64/runner/Release/
            dist/imajviewer_setup_*.exe

  create-release:
    needs: build-windows
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - uses: actions/checkout@v4

      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: imajViewer-windows
          path: release-artifacts/windows

      - name: Create Gitea Release
        uses: nicojeske/mirror-gitea-release@v1
        with:
          gitea_url: https://git.softmediadesign.com
          repo: git_alhan/imajviewer
          tag_name: ${{ github.ref_name }}
          release_name: "imajViewer ${{ github.ref_name }}"
          body: "Windows installer and build artifacts"
          files: release-artifacts/windows/**
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
