import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { markdownToHtml, fillEmployeeName, fillPosition, fillStartDate, fillSalary } from '@/lib/api-helpers/pdf'; export const dynamic = 'force-dynamic'; /** Parse and validate request params. Returns null if invalid (with response). */ function parseRequest(req: NextRequest) { const { searchParams } = new URL(req.url); const id = searchParams.get('id'); if (!id) return { error: NextResponse.json({ error: 'id required' }, { status: 400 }) }; const templateId = Number.parseInt(id, 10); if (Number.isNaN(templateId)) return { error: NextResponse.json({ error: 'Invalid id' }, { status: 400 }) }; return { templateId, employeeName: searchParams.get('employee') || '', position: searchParams.get('position') || '', startDate: searchParams.get('startDate') || '', salary: searchParams.get('salary') || '', }; } /** Build the full HTML page with styles. */ function buildFullHtml(html: string, template: { title: string; templateCode: string; charsCount: number }): string { return ` ${template.title} — Panya-AI ${html} `; } // GET /api/templates/pdf?id=123&employee=นาย+สมชาย+ใจดี export async function GET(req: NextRequest) { const parsed = parseRequest(req); if ('error' in parsed) return parsed.error; const template = await db.contractTemplate.findUnique({ where: { templateId: parsed.templateId } }); if (!template) return NextResponse.json({ error: 'Not found' }, { status: 404 }); let html = markdownToHtml(template.fullText || ''); html = fillEmployeeName(html, parsed.employeeName); html = fillPosition(html, parsed.position); html = fillStartDate(html, parsed.startDate); html = fillSalary(html, parsed.salary); const fullHtml = buildFullHtml(html, template); return new NextResponse(fullHtml, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, }); }