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

// Default branding values
const defaultBranding = {
  panelName: 'SKG UCP',
  logoUrl: null,
  backgroundUrl: null,
  primaryColor: '#3B82F6',
  secondaryColor: '#1E40AF',
  themeStyle: 'dark',
}

// Public endpoint - no auth required
export async function GET() {
  try {
    // Try to get branding from BrandingSetting table first
    const branding = await prisma.brandingSetting.findFirst()
    
    if (branding) {
      return NextResponse.json({
        panelName: branding.panelName || defaultBranding.panelName,
        logoUrl: branding.logoUrl || defaultBranding.logoUrl,
        backgroundUrl: branding.backgroundUrl || defaultBranding.backgroundUrl,
        primaryColor: branding.primaryColor || defaultBranding.primaryColor,
        secondaryColor: branding.secondaryColor || defaultBranding.secondaryColor,
        themeStyle: branding.themeStyle || defaultBranding.themeStyle,
      })
    }

    // Fallback: try to get from SystemSetting table (legacy support)
    const settings = await prisma.systemSetting.findMany({
      where: {
        key: {
          in: ['panelName', 'logoUrl', 'backgroundUrl', 'primaryColor', 'secondaryColor', 'themeStyle']
        }
      }
    })

    if (settings.length > 0) {
      const brandingMap: Record<string, string> = {}
      for (const setting of settings) {
        brandingMap[setting.key] = setting.value
      }

      return NextResponse.json({
        panelName: brandingMap.panelName || defaultBranding.panelName,
        logoUrl: brandingMap.logoUrl || defaultBranding.logoUrl,
        backgroundUrl: brandingMap.backgroundUrl || defaultBranding.backgroundUrl,
        primaryColor: brandingMap.primaryColor || defaultBranding.primaryColor,
        secondaryColor: brandingMap.secondaryColor || defaultBranding.secondaryColor,
        themeStyle: brandingMap.themeStyle || defaultBranding.themeStyle,
      })
    }

    // Return defaults if nothing found
    return NextResponse.json(defaultBranding)
  } catch (error) {
    console.error('[API] Branding fetch error:', error)
    // Return defaults on error (including when DATABASE_URL is not set)
    return NextResponse.json(defaultBranding)
  }
}
