import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    console.log('Fetching SEO data...')
    
    // Fetch SEO settings from database
    const settings = await db.systemSettings.findFirst({
      select: {
        siteName: true,
        metaTitle: true,
        metaDescription: true,
        metaKeywords: true,
        ogImage: true,
        heroTitle: true,
        heroDescription: true,
        contactEmail: true,
        contactPhone: true,
        address: true,
        workingHours: true,
        siteLogo: true,
        polresLogo: true,
      }
    })

    console.log('SEO settings fetched:', settings ? 'Found' : 'Not found')

    if (!settings) {
      return NextResponse.json(
        { error: 'SEO settings not found' },
        { status: 404 }
      )
    }

    // Transform settings for frontend consumption
    const seoData = {
      title: settings.metaTitle || settings.heroTitle || 'Polres Wonosobo - Sistem Pelayanan Digital',
      description: settings.metaDescription || settings.heroDescription || 'Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya',
      keywords: settings.metaKeywords || 'polres wonosobo, pelayanan polisi, pengajuan dokumen, kepolisian',
      ogImage: settings.ogImage || '/og-default.jpg',
      siteName: settings.siteName || 'Polres Wonosobo',
      siteUrl: 'https://polres-wonosobo.example.com',
      logo: settings.siteLogo || '/logo.png',
      contact: {
        email: settings.contactEmail,
        phone: settings.contactPhone,
        address: settings.address,
        workingHours: settings.workingHours,
      },
      organization: {
        name: settings.siteName || 'Polres Wonosobo',
        logo: settings.polresLogo || settings.siteLogo || '/logo.png',
        description: settings.heroDescription || 'Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya',
      }
    }

    console.log('SEO data prepared successfully')

    // Add CORS headers for public API
    const headers = new Headers({
      'Content-Type': 'application/json',
      'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400', // Cache for 1 hour, serve stale for 24 hours
    })

    return NextResponse.json(seoData, {
      status: 200,
      headers,
    })
  } catch (error) {
    console.error('Error fetching SEO data:', error)
    return NextResponse.json(
      { error: 'Failed to fetch SEO data', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}