# Staging: build backend/frontend images, push to Gitea Container Registry, deploy on self-hosted runner.
#
# Triggers: push to master/main, or manual workflow_dispatch.
# Production (nudentic.ir / git tags): .gitea/workflows/prod-tag-deploy.yml — this file is Windows staging only.
#
# Repository Variables (Settings → Actions → Variables):
#   REGISTRY_HOST        Docker registry host:port (no http/https).
#                        Windows Docker Desktop → host.docker.internal:3000
#                        Do NOT use gitea.wixur.ir unless Windows nginx for that
#                        host has client_max_body_size 0 — Docker layer PUTs 413 otherwise.
#   REGISTRY_OWNER       Gitea user or org that owns the packages
#   PUBLIC_BASE_URL      URL users open in the browser, e.g. http://wixur.ir  (no trailing slash, no :8088)
#   NEXT_PUBLIC_SENTRY_DSN  GlitchTip frontend project DSN (https://…@errors.wixur.ir/…)
#   DEPLOY_SECRETS_DIR   absolute path on runner, e.g. C:/dyolink/secrets
#
# Optional:
#   STAGING_HTTP_PORT    public HTTP port (default 80) — Windows portproxy listens here → 18088
#   STAGING_LOCAL_PORT   Docker bind on 127.0.0.1 (default 18088) — must not equal the public port if portproxy owns it
#   CLONE_HOST           git clone host when runner = Gitea host → 127.0.0.1:3000
#   NODE_IMAGE_SOURCE    extra base-image ref(s), comma-separated, tried before built-in mirrors
#                        e.g. docker.arvancloud.ir/library/node:20-alpine
#
# Same Windows PC runs Gitea + runner + deploy:
#   CLONE_HOST           → 127.0.0.1:3000  (git runs on Windows host)
#   REGISTRY_HOST        → host.docker.internal:3000  (docker commands run inside Docker Desktop VM)
#   Gitea app.ini ROOT_URL → http://host.docker.internal:3000/  (Docker registry auth; browsers use http://wixur.ir:3000)
#   PUBLIC_BASE_URL      → http://wixur.ir  (staging app; Gitea stays on :3000)
#
# Add host.docker.internal:3000 (and wixur.ir:3000 if you pull by public hostname) to Docker Desktop insecure-registries.
#
# Repository Secrets (Settings → Actions → Secrets):
#   REGISTRY_USERNAME    Gitea username for docker login
#   REGISTRY_PASSWORD    Gitea access token (packages:read/write) or account password
#
# Docker on runner: insecure-registries e.g. ["host.docker.internal:3000","wixur.ir:3000"]
#
# Runner: self-hosted with Docker + git. Default shell is powershell (Windows act_runner).
# Windows PowerShell 5.1 does not fail a step when docker/git return non-zero — always check $LASTEXITCODE.

name: Registry — build, push, deploy

on:
  push:
    branches: [main, master]
  workflow_dispatch:

defaults:
  run:
    shell: powershell

jobs:
  build-and-push:
    runs-on: windows
    steps:
      - name: Checkout (clone from this Gitea — no gitea.com)
        run: |
          $ErrorActionPreference = 'Stop'
          $cloneHost = '${{ vars.CLONE_HOST }}'.Trim()
          if ([string]::IsNullOrWhiteSpace($cloneHost)) {
            $Server = "${{ github.server_url }}".TrimEnd('/')
          } elseif ($cloneHost -match '^https?://') {
            $Server = $cloneHost.TrimEnd('/')
          } else {
            $Server = 'http://' + $cloneHost
          }
          $Repo = "${{ github.repository }}"
          $Branch = "${{ github.ref_name }}"
          $Token = "${{ github.token }}"
          $Actor = "${{ github.actor }}"
          $hp = $Server -replace '^https?://', ''
          if ($Server.StartsWith('https')) {
            $cloneUrl = 'https://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git'
          } else {
            $cloneUrl = 'http://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git'
          }
          $env:GIT_TERMINAL_PROMPT = '0'
          git clone --depth 1 --branch $Branch $cloneUrl .
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Log in to container registry
        run: |
          $ErrorActionPreference = 'Stop'
          $pass = @'
          ${{ secrets.REGISTRY_PASSWORD }}
          '@
          $pass.Trim() | docker login "${{ vars.REGISTRY_HOST }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Resolve node:20-alpine (Gitea, then mirrors, Hub last)
        run: |
          $ErrorActionPreference = 'Stop'
          $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim()
          $extra = '${{ vars.NODE_IMAGE_SOURCE }}'.Trim()
          if ($extra -like '*NODE_IMAGE_SOURCE*') { $extra = '' }
          # Do not nest powershell -File: empty -ExtraSources "$extra" is dropped and PS5.1 errors MissingArgument.
          $scriptArgs = @{ RegistryPrefix = $prefix }
          if (-not [string]::IsNullOrWhiteSpace($extra)) { $scriptArgs['ExtraSources'] = $extra }
          & .\infrastructure\scripts\ci-resolve-node-image.ps1 @scriptArgs
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Build and push backend
        run: |
          $ErrorActionPreference = 'Stop'
          $tag = "${{ github.sha }}".Substring(0, 7)
          $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim()
          if ([string]::IsNullOrWhiteSpace($tag) -or [string]::IsNullOrWhiteSpace($prefix)) {
            Write-Host "Missing github.sha, REGISTRY_HOST, or REGISTRY_OWNER"
            exit 1
          }
          $nodeImage = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-node-image'))).Trim()
          if ([string]::IsNullOrWhiteSpace($nodeImage)) {
            Write-Host "Missing .ci-node-image"
            exit 1
          }
          if (Test-Path '.ci-use-legacy-builder') { $env:DOCKER_BUILDKIT = '0' }
          Write-Host "Building $prefix/dyolink-backend:$tag (NODE_IMAGE=$nodeImage)"
          $ok = $false
          for ($i = 1; $i -le 3; $i++) {
            Write-Host "docker build attempt $i/3"
            docker build `
              --build-arg "NODE_IMAGE=$nodeImage" `
              -t "$prefix/dyolink-backend:$tag" `
              -t "$prefix/dyolink-backend:latest" `
              ./backend
            if ($LASTEXITCODE -eq 0) { $ok = $true; break }
            if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
          }
          if (-not $ok) { exit 1 }
          docker push "$prefix/dyolink-backend:$tag"
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
          docker push "$prefix/dyolink-backend:latest"
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Build and push frontend
        env:
          PUBLIC_BASE_URL: ${{ vars.PUBLIC_BASE_URL }}
          NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
        run: |
          $ErrorActionPreference = 'Stop'
          $tag = "${{ github.sha }}".Substring(0, 7)
          $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim()
          $base = $env:PUBLIC_BASE_URL
          $nodeImage = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-node-image'))).Trim()
          if ([string]::IsNullOrWhiteSpace($nodeImage)) {
            Write-Host "Missing .ci-node-image"
            exit 1
          }
          if (Test-Path '.ci-use-legacy-builder') { $env:DOCKER_BUILDKIT = '0' }
          Write-Host "Building $prefix/dyolink-frontend:$tag (NODE_IMAGE=$nodeImage)"
          $ok = $false
          for ($i = 1; $i -le 3; $i++) {
            Write-Host "docker build attempt $i/3"
            docker build `
              --build-arg "NEXT_PUBLIC_API_URL=$base/api" `
              --build-arg "NEXT_PUBLIC_APP_URL=$base" `
              --build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
              --build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
              --build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=staging" `
              --build-arg "NODE_IMAGE=$nodeImage" `
              -t "$prefix/dyolink-frontend:$tag" `
              -t "$prefix/dyolink-frontend:latest" `
              ./frontend
            if ($LASTEXITCODE -eq 0) { $ok = $true; break }
            if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
          }
          if (-not $ok) { exit 1 }
          docker push "$prefix/dyolink-frontend:$tag"
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
          docker push "$prefix/dyolink-frontend:latest"
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

  deploy:
    needs: build-and-push
    runs-on: windows
    steps:
      - name: Checkout (shallow clone from this Gitea — no gitea.com)
        run: |
          $ErrorActionPreference = 'Stop'
          $cloneHost = '${{ vars.CLONE_HOST }}'.Trim()
          if ([string]::IsNullOrWhiteSpace($cloneHost)) {
            $Server = "${{ github.server_url }}".TrimEnd('/')
          } elseif ($cloneHost -match '^https?://') {
            $Server = $cloneHost.TrimEnd('/')
          } else {
            $Server = 'http://' + $cloneHost
          }
          $Repo = "${{ github.repository }}"
          $Branch = "${{ github.ref_name }}"
          $Token = "${{ github.token }}"
          $Actor = "${{ github.actor }}"
          $hp = $Server -replace '^https?://', ''
          if ($Server.StartsWith('https')) {
            $cloneUrl = 'https://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git'
          } else {
            $cloneUrl = 'http://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git'
          }
          $env:GIT_TERMINAL_PROMPT = '0'
          git clone --depth 1 --branch $Branch $cloneUrl .
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Write deploy.registry.env and validate secrets path
        run: |
          $ErrorActionPreference = 'Stop'
          $SD = '${{ vars.DEPLOY_SECRETS_DIR }}'.Trim()
          if ([string]::IsNullOrWhiteSpace($SD)) {
            Write-Host "Set repository variable DEPLOY_SECRETS_DIR to the absolute path on this runner"
            Write-Host "where database.staging.env and backend.staging.env live (not in git)."
            exit 1
          }
          if (-not (Test-Path (Join-Path $SD "database.staging.env"))) {
            Write-Host "Missing $(Join-Path $SD 'database.staging.env')"
            exit 1
          }
          if (-not (Test-Path (Join-Path $SD "backend.staging.env"))) {
            Write-Host "Missing $(Join-Path $SD 'backend.staging.env')"
            exit 1
          }
          $stagingPort = '${{ vars.STAGING_HTTP_PORT }}'.Trim()
          if ([string]::IsNullOrWhiteSpace($stagingPort)) { $stagingPort = '80' }
          $localPort = '${{ vars.STAGING_LOCAL_PORT }}'.Trim()
          if ([string]::IsNullOrWhiteSpace($localPort)) { $localPort = '18088' }
          $imageTag = "${{ github.sha }}".Substring(0, 7)
          $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim()
          Write-Host "IMAGE_TAG=$imageTag REGISTRY_PREFIX=$prefix"
          $lines = @(
            "REGISTRY_PREFIX=$prefix",
            "IMAGE_TAG=$imageTag",
            "STAGING_HTTP_PORT=$stagingPort",
            "STAGING_LOCAL_PORT=$localPort",
            "DEPLOY_SECRETS_DIR=$SD"
          )
          Set-Location infrastructure
          $utf8 = New-Object System.Text.UTF8Encoding $false
          [System.IO.File]::WriteAllText((Join-Path (Get-Location) 'deploy.registry.env'), ($lines -join "`n") + "`n", $utf8)

      - name: Log in to container registry (for pull)
        run: |
          $ErrorActionPreference = 'Stop'
          $pass = @'
          ${{ secrets.REGISTRY_PASSWORD }}
          '@
          $pass.Trim() | docker login "${{ vars.REGISTRY_HOST }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Pull and start stack
        run: |
          $ErrorActionPreference = 'Stop'
          Set-Location infrastructure
          docker compose -f docker-compose.registry.yml --env-file deploy.registry.env pull backend frontend
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
          docker compose -f docker-compose.registry.yml --env-file deploy.registry.env up -d
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
