## Task 5: Trigger della GitHub Action

**Files:**
- Create: `app/src/lib/server/pdf/dispatch.ts`
- Create: `app/src/lib/server/pdf/dispatch.test.ts`

**Interfaces:**
- Produces: `export async function triggerPdfGeneration(agenziaId: number): Promise<void>` — chiama `POST https://api.github.com/repos/paoloalby/alleanza-dvr/dispatches` con `event_type: 'generate-dvr-pdf'`, `client_payload: { agenzia_id }`, header `Authorization: Bearer ${GITHUB_DISPATCH_TOKEN}`, `Accept: application/vnd.github+json`.
- **Env richiesta su Vercel:** `GITHUB_DISPATCH_TOKEN` (PAT fine-grained con permesso "Contents: read & write" o "Actions: read & write" sul repo).

- [ ] **Step 1: Test che costruisca la richiesta corretta (mock fetch)**

Crea `app/src/lib/server/pdf/dispatch.test.ts`:

```ts
import { describe, it, expect, vi, beforeEach } from 'vitest';

vi.mock('$env/dynamic/private', () => ({ env: { GITHUB_DISPATCH_TOKEN: 'tok' } }));

describe('triggerPdfGeneration', () => {
	beforeEach(() => vi.restoreAllMocks());
	it('POSTa il repository_dispatch con il payload giusto', async () => {
		const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 204 });
		vi.stubGlobal('fetch', fetchMock);
		const { triggerPdfGeneration } = await import('./dispatch');
		await triggerPdfGeneration(467);
		const [url, opts] = fetchMock.mock.calls[0];
		expect(url).toBe('https://api.github.com/repos/paoloalby/alleanza-dvr/dispatches');
		expect(opts.method).toBe('POST');
		expect(JSON.parse(opts.body)).toEqual({ event_type: 'generate-dvr-pdf', client_payload: { agenzia_id: 467 } });
		expect(opts.headers.Authorization).toBe('Bearer tok');
	});
});
```

- [ ] **Step 2: Esegui e verifica fallimento**

Run: `cd app && npx vitest run src/lib/server/pdf/dispatch.test.ts`
Expected: FAIL (modulo inesistente).

- [ ] **Step 3: Implementa `dispatch.ts`**

```ts
import { env } from '$env/dynamic/private';

const REPO = 'paoloalby/alleanza-dvr';

export async function triggerPdfGeneration(agenziaId: number): Promise<void> {
	const token = env.GITHUB_DISPATCH_TOKEN;
	if (!token) throw new Error('GITHUB_DISPATCH_TOKEN mancante');
	const res = await fetch(`https://api.github.com/repos/${REPO}/dispatches`, {
		method: 'POST',
		headers: {
			Authorization: `Bearer ${token}`,
			Accept: 'application/vnd.github+json',
			'Content-Type': 'application/json',
			'User-Agent': 'alleanza-dvr'
		},
		body: JSON.stringify({ event_type: 'generate-dvr-pdf', client_payload: { agenzia_id: agenziaId } })
	});
	if (!res.ok) throw new Error(`Dispatch fallito: ${res.status}`);
}
```

- [ ] **Step 4: Esegui e verifica passaggio**

Run: `cd app && npx vitest run src/lib/server/pdf/dispatch.test.ts`
Expected: PASS.

- [ ] **Step 5: Commit**

```bash
git add app/src/lib/server/pdf/dispatch.ts app/src/lib/server/pdf/dispatch.test.ts
git commit -m "PDF: trigger GitHub Action via repository_dispatch"
```

---

