import { NextRequest, NextResponse } from 'next/server';
import { getLandingPage, updateLandingPage, deleteLandingPage } from '@/lib/db';
import { generateAllPages } from '@/lib/landing-page-generator';
import type { LandingPageConfig } from '@/lib/landing-page-generator';

export async function GET(
  _req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const page = getLandingPage(params.id);
    if (!page) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    return NextResponse.json({ page });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const existing = getLandingPage(params.id);
    if (!existing) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }

    const body = await req.json();
    const config: LandingPageConfig = {
      businessName: body.businessName ?? existing.business_name,
      businessSlug: body.businessSlug ?? existing.business_slug,
      useCase: body.useCase ?? JSON.parse(existing.config_json).useCase,
      messageFrequency: body.messageFrequency ?? JSON.parse(existing.config_json).messageFrequency,
      contactEmail: body.contactEmail ?? JSON.parse(existing.config_json).contactEmail,
      contactPhone: body.contactPhone ?? JSON.parse(existing.config_json).contactPhone,
      brandColor: body.brandColor ?? JSON.parse(existing.config_json).brandColor,
      logoUrl: body.logoUrl ?? JSON.parse(existing.config_json).logoUrl,
    };

    const pages = generateAllPages(config);

    updateLandingPage(params.id, {
      business_name: config.businessName,
      business_slug: config.businessSlug,
      config_json: JSON.stringify(config),
      opt_in_html: pages.optIn,
      privacy_html: pages.privacyPolicy,
      terms_html: pages.terms,
      status: body.status,
    });

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

export async function DELETE(
  _req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const existing = getLandingPage(params.id);
    if (!existing) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    deleteLandingPage(params.id);
    return NextResponse.json({ success: true });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
