import { NextRequest, NextResponse } from 'next/server';
import { listLandingPages, createLandingPage } from '@/lib/db';
import { generateAllPages, generateSlug } from '@/lib/landing-page-generator';
import type { LandingPageConfig } from '@/lib/landing-page-generator';

export async function GET(req: NextRequest) {
  try {
    const url = new URL(req.url);
    const status = url.searchParams.get('status') || undefined;
    const limit = parseInt(url.searchParams.get('limit') || '50', 10);
    const offset = parseInt(url.searchParams.get('offset') || '0', 10);

    const pages = listLandingPages({ status, limit, offset });
    // Strip HTML content from list view for performance
    const lightPages = pages.map(({ opt_in_html, privacy_html, terms_html, ...rest }) => rest);
    return NextResponse.json({ pages: lightPages });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const {
      businessName,
      businessSlug,
      useCase,
      messageFrequency,
      contactEmail,
      contactPhone,
      brandColor,
      logoUrl,
      a2pRegistrationId,
    } = body;

    if (!businessName || !useCase || !messageFrequency || !contactEmail || !contactPhone) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const slug = businessSlug || generateSlug(businessName);

    const config: LandingPageConfig = {
      businessName,
      businessSlug: slug,
      useCase,
      messageFrequency,
      contactEmail,
      contactPhone,
      brandColor: brandColor || '#3B82F6',
      logoUrl: logoUrl || undefined,
    };

    const pages = generateAllPages(config);

    const id = Math.random().toString(36).slice(2, 10) + Date.now().toString(36);

    createLandingPage({
      id,
      business_name: businessName,
      business_slug: slug,
      config_json: JSON.stringify(config),
      opt_in_html: pages.optIn,
      privacy_html: pages.privacyPolicy,
      terms_html: pages.terms,
      status: 'draft',
      a2p_registration_id: a2pRegistrationId,
    });

    return NextResponse.json({ id, slug, status: 'draft' }, { status: 201 });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
