#!/usr/bin/env sh
set -eu

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"

find app database routes config tests -name '*.php' -print0 | xargs -0 -n1 php -l >/tmp/digital-dossier-communications-php.txt

for file in \
  app/Http/Controllers/CommunicationBatchController.php \
  app/Http/Controllers/PublicCommunicationTrackingController.php \
  app/Http/Controllers/CommunicationWebhookController.php \
  app/Jobs/DispatchCommunicationBatch.php \
  app/Jobs/SendCommunicationRecipient.php \
  app/Services/Communications/CommunicationAudienceResolver.php \
  app/Services/Communications/CommunicationTrackingService.php \
  app/Services/Communications/CommunicationWebhookService.php \
  database/migrations/2026_08_06_000900_create_bulk_communications_tables.php \
  resources/views/communications/create.blade.php \
  config/communications.php \
  docs/BULK-COMMUNICATIONS.md; do
  test -s "$file" || { echo "Ficheiro obrigatório em falta: $file" >&2; exit 1; }
done

grep -q "module:workflow.*tenant_role" routes/web.php
grep -q "communications:dispatch-scheduled" routes/console.php
grep -q "communications:maintain" routes/console.php
grep -q "COMMUNICATION_WEBHOOK_SECRET" .env.example
grep -q "communications,signatures,pdf,default" docker-compose.yml
grep -q "tracking_token_hash" database/migrations/2026_08_06_000900_create_bulk_communications_tables.php
grep -q "List-Unsubscribe-Post" app/Mail/BatchCommunicationMail.php
grep -q "hash_hmac('sha256'" app/Services/Communications/CommunicationWebhookService.php
grep -q "unique.*communication_batch_id.*email_normalized" database/migrations/2026_08_06_000900_create_bulk_communications_tables.php

if grep -R -nE '^(<<<<<<<|=======|>>>>>>>)' app database routes config resources tests docs scripts; then
  echo "Foram encontrados marcadores de conflito." >&2
  exit 1
fi

printf 'Validação estática de comunicações concluída: %s ficheiros PHP.\n' "$(find app database routes config tests -name '*.php' | wc -l | tr -d ' ')"
