import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { verifyAdminToken } from '@/lib/admin-auth'

export async function GET(request: NextRequest) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    // Get settings from database
    let settings = await db.systemSettings.findFirst()
    
    // If no settings exist, create default settings
    if (!settings) {
      settings = await db.systemSettings.create({
        data: {
          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',
          timezone: 'Asia/Jakarta',
          language: 'id',
          emailNotifications: true,
          smsNotifications: false,
          autoAssignment: false,
          maintenanceMode: false,
          maxFileSize: 50,
          allowedFileTypes: ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'],
          sessionTimeout: 8,
          passwordMinLength: 8,
          requireEmailVerification: true,
          // 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',
          // Kapolres profile defaults
          kapolresName: 'AKBP. Dr. Budi Purnama, S.I.K., M.H.',
          kapolresNRP: '87050168',
          kapolresPangkat: 'AKBP',
          // Nomor pengajuan format defaults
          requestNumberFormat: 'SR-{YYYY}{MM}{DD}-{seq:4}',
          requestNumberSequence: 1,
          requestNumberReset: 'daily',
          skckNumberFormat: 'SKCK-{YYYY}{MM}{DD}-{seq:4}',
          spktNumberFormat: 'SPKT-{YYYY}{MM}{DD}-{seq:4}',
          lalinNumberFormat: 'LL-{YYYY}{MM}{DD}-{seq:4}',
          skckSequence: 1,
          spktSequence: 1,
          lalinSequence: 1
        }
      })
    }

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

export async function PUT(request: NextRequest) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const body = await request.json()
    
    // Validate required fields
    const { siteName, contactEmail, contactPhone } = body
    if (!siteName || !contactEmail || !contactPhone) {
      return NextResponse.json(
        { error: 'Nama situs, email kontak, dan telepon kontak wajib diisi' },
        { status: 400 }
      )
    }

    // Check if settings exist
    let existingSettings = await db.systemSettings.findFirst()
    
    if (existingSettings) {
      // Update existing settings
      const updatedSettings = await db.systemSettings.update({
        where: { id: existingSettings.id },
        data: {
          siteName,
          siteDescription: body.siteDescription || existingSettings.siteDescription,
          contactEmail,
          contactPhone,
          contactWhatsApp: body.contactWhatsApp || existingSettings.contactWhatsApp,
          address: body.address || existingSettings.address,
          workingHours: body.workingHours || existingSettings.workingHours,
          timezone: body.timezone || existingSettings.timezone,
          language: body.language || existingSettings.language,
          emailNotifications: body.emailNotifications !== undefined ? body.emailNotifications : existingSettings.emailNotifications,
          smsNotifications: body.smsNotifications !== undefined ? body.smsNotifications : existingSettings.smsNotifications,
          autoAssignment: body.autoAssignment !== undefined ? body.autoAssignment : existingSettings.autoAssignment,
          maintenanceMode: body.maintenanceMode !== undefined ? body.maintenanceMode : existingSettings.maintenanceMode,
          maxFileSize: body.maxFileSize !== undefined ? body.maxFileSize : existingSettings.maxFileSize,
          allowedFileTypes: body.allowedFileTypes || existingSettings.allowedFileTypes,
          sessionTimeout: body.sessionTimeout !== undefined ? body.sessionTimeout : existingSettings.sessionTimeout,
          passwordMinLength: body.passwordMinLength !== undefined ? body.passwordMinLength : existingSettings.passwordMinLength,
          requireEmailVerification: body.requireEmailVerification !== undefined ? body.requireEmailVerification : existingSettings.requireEmailVerification,
          // Hero section fields
          heroTitle: body.heroTitle !== undefined ? body.heroTitle : existingSettings.heroTitle,
          heroSubtitle: body.heroSubtitle !== undefined ? body.heroSubtitle : existingSettings.heroSubtitle,
          heroDescription: body.heroDescription !== undefined ? body.heroDescription : existingSettings.heroDescription,
          heroBackgroundImage: body.heroBackgroundImage !== undefined ? body.heroBackgroundImage : existingSettings.heroBackgroundImage,
          heroButtonText: body.heroButtonText !== undefined ? body.heroButtonText : existingSettings.heroButtonText,
          heroButtonLink: body.heroButtonLink !== undefined ? body.heroButtonLink : existingSettings.heroButtonLink,
          heroSecondaryButtonText: body.heroSecondaryButtonText !== undefined ? body.heroSecondaryButtonText : existingSettings.heroSecondaryButtonText,
          heroSecondaryButtonLink: body.heroSecondaryButtonLink !== undefined ? body.heroSecondaryButtonLink : existingSettings.heroSecondaryButtonLink,
          // Branding fields
          siteLogo: body.siteLogo !== undefined ? body.siteLogo : existingSettings.siteLogo,
          siteIcon: body.siteIcon !== undefined ? body.siteIcon : existingSettings.siteIcon,
          polresLogo: body.polresLogo !== undefined ? body.polresLogo : existingSettings.polresLogo,
          polresLogo2: body.polresLogo2 !== undefined ? body.polresLogo2 : existingSettings.polresLogo2,
          runningText: body.runningText !== undefined ? body.runningText : existingSettings.runningText,
          // SEO fields
          metaTitle: body.metaTitle !== undefined ? body.metaTitle : existingSettings.metaTitle,
          metaDescription: body.metaDescription !== undefined ? body.metaDescription : existingSettings.metaDescription,
          metaKeywords: body.metaKeywords !== undefined ? body.metaKeywords : existingSettings.metaKeywords,
          ogImage: body.ogImage !== undefined ? body.ogImage : existingSettings.ogImage,
          // Kapolres profile fields
          kapolresName: body.kapolresName !== undefined ? body.kapolresName : existingSettings.kapolresName,
          kapolresNRP: body.kapolresNRP !== undefined ? body.kapolresNRP : existingSettings.kapolresNRP,
          kapolresPangkat: body.kapolresPangkat !== undefined ? body.kapolresPangkat : existingSettings.kapolresPangkat,
          kapolresSignature: body.kapolresSignature !== undefined ? body.kapolresSignature : existingSettings.kapolresSignature,
          // Nomor pengajuan format fields
          requestNumberFormat: body.requestNumberFormat !== undefined ? body.requestNumberFormat : existingSettings.requestNumberFormat,
          requestNumberSequence: body.requestNumberSequence !== undefined ? body.requestNumberSequence : existingSettings.requestNumberSequence,
          requestNumberReset: body.requestNumberReset !== undefined ? body.requestNumberReset : existingSettings.requestNumberReset,
          skckNumberFormat: body.skckNumberFormat !== undefined ? body.skckNumberFormat : existingSettings.skckNumberFormat,
          spktNumberFormat: body.spktNumberFormat !== undefined ? body.spktNumberFormat : existingSettings.spktNumberFormat,
          lalinNumberFormat: body.lalinNumberFormat !== undefined ? body.lalinNumberFormat : existingSettings.lalinNumberFormat,
          skckSequence: body.skckSequence !== undefined ? body.skckSequence : existingSettings.skckSequence,
          spktSequence: body.spktSequence !== undefined ? body.spktSequence : existingSettings.spktSequence,
          lalinSequence: body.lalinSequence !== undefined ? body.lalinSequence : existingSettings.lalinSequence,
        }
      })

      return NextResponse.json({
        success: true,
        settings: updatedSettings,
        message: 'Pengaturan berhasil diperbarui'
      })
    } else {
      // Create new settings
      const newSettings = await db.systemSettings.create({
        data: {
          siteName,
          siteDescription: body.siteDescription || 'Sistem Pelayanan Digital Polres Wonosobo',
          contactEmail,
          contactPhone,
          contactWhatsApp: body.contactWhatsApp || '+62 812-3456-7890',
          address: body.address || 'Jl. Pahlawan No. 15, Wonosobo',
          workingHours: body.workingHours || 'Senin - Jumat: 08:00 - 16:00',
          timezone: body.timezone || 'Asia/Jakarta',
          language: body.language || 'id',
          emailNotifications: body.emailNotifications !== undefined ? body.emailNotifications : true,
          smsNotifications: body.smsNotifications !== undefined ? body.smsNotifications : false,
          autoAssignment: body.autoAssignment !== undefined ? body.autoAssignment : false,
          maintenanceMode: body.maintenanceMode !== undefined ? body.maintenanceMode : false,
          maxFileSize: body.maxFileSize !== undefined ? body.maxFileSize : 5,
          allowedFileTypes: body.allowedFileTypes || ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'],
          sessionTimeout: body.sessionTimeout !== undefined ? body.sessionTimeout : 8,
          passwordMinLength: body.passwordMinLength !== undefined ? body.passwordMinLength : 8,
          requireEmailVerification: body.requireEmailVerification !== undefined ? body.requireEmailVerification : true,
          // Hero section fields
          heroTitle: body.heroTitle !== undefined ? body.heroTitle : 'Sistem Pelayanan Digital',
          heroSubtitle: body.heroSubtitle !== undefined ? body.heroSubtitle : 'Polres Wonosobo',
          heroDescription: body.heroDescription !== undefined ? body.heroDescription : 'Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya',
          heroBackgroundImage: body.heroBackgroundImage !== undefined ? body.heroBackgroundImage : '/hero-bg.jpg',
          heroButtonText: body.heroButtonText !== undefined ? body.heroButtonText : 'Lihat Layanan',
          heroButtonLink: body.heroButtonLink !== undefined ? body.heroButtonLink : '#layanan',
          heroSecondaryButtonText: body.heroSecondaryButtonText !== undefined ? body.heroSecondaryButtonText : 'Lacak Pengajuan',
          heroSecondaryButtonLink: body.heroSecondaryButtonLink !== undefined ? body.heroSecondaryButtonLink : '/lacak',
          // Branding fields
          siteLogo: body.siteLogo || null,
          siteIcon: body.siteIcon || null,
          polresLogo: body.polresLogo || null,
          polresLogo2: body.polresLogo2 || null,
          runningText: body.runningText || null,
          // SEO fields
          metaTitle: body.metaTitle || null,
          metaDescription: body.metaDescription || null,
          metaKeywords: body.metaKeywords || null,
          ogImage: body.ogImage || null,
          // Kapolres profile fields
          kapolresName: body.kapolresName || 'AKBP. Dr. Budi Purnama, S.I.K., M.H.',
          kapolresNRP: body.kapolresNRP || '87050168',
          kapolresPangkat: body.kapolresPangkat || 'AKBP',
          kapolresSignature: body.kapolresSignature || null,
          // Nomor pengajuan format fields
          requestNumberFormat: body.requestNumberFormat || 'SR-{YYYY}{MM}{DD}-{seq:4}',
          requestNumberSequence: body.requestNumberSequence || 1,
          requestNumberReset: body.requestNumberReset || 'daily',
          skckNumberFormat: body.skckNumberFormat || 'SKCK-{YYYY}{MM}{DD}-{seq:4}',
          spktNumberFormat: body.spktNumberFormat || 'SPKT-{YYYY}{MM}{DD}-{seq:4}',
          lalinNumberFormat: body.lalinNumberFormat || 'LL-{YYYY}{MM}{DD}-{seq:4}',
          skckSequence: body.skckSequence || 1,
          spktSequence: body.spktSequence || 1,
          lalinSequence: body.lalinSequence || 1,
        }
      })

      return NextResponse.json({
        success: true,
        settings: newSettings,
        message: 'Pengaturan berhasil disimpan'
      })
    }
  } catch (error) {
    console.error('Error updating settings:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat memperbarui pengaturan' },
      { status: 500 }
    )
  }
}