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

export async function GET(request: NextRequest) {
  try {
    // Get settings from database
    let settings = await db.systemSettings.findFirst()
    
    // If no settings exist, return default settings
    if (!settings) {
      const publicSettings = {
        siteName: 'Polres Wonosobo',
        siteDescription: 'Sistem Pelayanan Digital Polres Wonosobo',
        contactEmail: 'polreswonosobo@polri.go.id',
        contactPhone: '(0286) 321001',
        contactWhatsApp: '+62 812-3456-7890',
        address: 'Jl. Pahlawan No. 15, Wonosobo',
        workingHours: 'Senin - Jumat: 08:00 - 16:00',
        siteLogo: null,
        polresLogo: null,
        polresLogo2: null,
        // Hero section defaults
        heroTitle: 'Sistem Pelayanan Digital',
        heroSubtitle: 'Polres Wonosobo',
        heroDescription: 'Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya',
        heroBackgroundImage: '/hero-bg.jpg',
        heroButtonText: 'Lihat Layanan',
        heroButtonLink: '#layanan',
        heroSecondaryButtonText: 'Lacak Pengajuan',
        heroSecondaryButtonLink: '/lacak',
        // Running text
        runningText: null
      }
      
      return NextResponse.json({
        success: true,
        settings: publicSettings
      })
    }

    // Return only public-safe settings
    const publicSettings = {
      siteName: settings.siteName,
      siteDescription: settings.siteDescription,
      contactEmail: settings.contactEmail,
      contactPhone: settings.contactPhone,
      contactWhatsApp: settings.contactWhatsApp,
      address: settings.address,
      workingHours: settings.workingHours,
      siteLogo: settings.siteLogo,
      polresLogo: settings.polresLogo,
      polresLogo2: settings.polresLogo2,
      // Hero section settings
      heroTitle: settings.heroTitle,
      heroSubtitle: settings.heroSubtitle,
      heroDescription: settings.heroDescription,
      heroBackgroundImage: settings.heroBackgroundImage,
      heroButtonText: settings.heroButtonText,
      heroButtonLink: settings.heroButtonLink,
      heroSecondaryButtonText: settings.heroSecondaryButtonText,
      heroSecondaryButtonLink: settings.heroSecondaryButtonLink,
      // Running text
      runningText: settings.runningText
    }

    return NextResponse.json({
      success: true,
      settings: publicSettings
    })
  } catch (error) {
    console.error('Error fetching public settings:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat mengambil pengaturan' },
      { status: 500 }
    )
  }
}