import { NextRequest, NextResponse } from 'next/server';
import puppeteer from 'puppeteer';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const title = req.nextUrl.searchParams.get('title') ?? '';
  const desc = req.nextUrl.searchParams.get('description') ?? '';

  const imageUrl = `${req.nextUrl.origin}/images/ogBg.png`;
  const logoUrl = `${req.nextUrl.origin}/images/logo-dtr-white.png`;

  const html = `
    <html lang="ru-RU">
      <body style="
        margin: 0;
        padding: 0;
        display: flex;
        width: 600px;
        height: 315px;
        background: #111;
        color: white;
        font-family: sans-serif;
        position: relative;
      ">
        <img src="${imageUrl}" style="object-fit: cover; width:100%; height:100%; opacity:0.5; position:absolute; left:0; top:0;" />
        <img src="${logoUrl}" style="width: 288px; height: 89px; position:absolute; left:10px; top:20px;" />
        <p style="position: absolute; top: 24px; right:20px; color: white; font-family: Arial, Helvetica, sans-serif; font-size: 20px;  ">
        ☎ +7 (900) 241-34-34
        </p>
        <div style="position: absolute; top: 140px; left: 20px; width:100%; height:100%;">
        <h2 style="color: white; font-family: Arial, Helvetica, sans-serif; font-size: 40px; line-height: 1;">${title}</h2>
        <p style="color: white; font-family: Arial, Helvetica, sans-serif; font-size: 24px;  line-height: 1;">${desc}</p>
      </div>
      </body>
    </html>
    `;

  // Запуск браузера
  const browser = await puppeteer.launch({
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'networkidle0' });
  await page.setViewport({ width: 600, height: 315 });
  const screenshot = await page.screenshot({ type: 'png' });
  await browser.close();

  return new NextResponse(screenshot, {
    headers: {
      'Content-Type': 'image/png',
      'Cache-Control': 'max-age=60',
    },
  });
}
