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

export async function GET() {
  try {
    // Fetch active Polres data
    const polresList = await db.polres.findMany({
      where: { isActive: true },
      orderBy: { order: 'asc' },
      select: {
        id: true,
        name: true,
        address: true,
        phone: true,
        email: true,
        kapolresName: true,
        kapolresPangkat: true,
      }
    })

    // Fetch active Polsek data with their Polres
    const polsekList = await db.polsek.findMany({
      where: { isActive: true },
      orderBy: { order: 'asc' },
      include: {
        polres: {
          select: {
            name: true,
          }
        }
      }
    })

    // Format the data for frontend consumption
    const locations = [
      ...polresList.map(polres => ({
        id: polres.id,
        name: `POLRES ${polres.name}`,
        type: 'polres',
        address: polres.address,
        phone: polres.phone,
        email: polres.email,
        chief: `${polres.kapolresPangkat} ${polres.kapolresName}`.trim(),
      })),
      ...polsekList.map(polsek => ({
        id: polsek.id,
        name: `POLSEK ${polsek.name}`,
        type: 'polsek',
        address: polsek.address,
        phone: polsek.phone,
        email: polsek.email,
        chief: `${polsek.kapolsekPangkat} ${polsek.kapolsekName}`.trim(),
        polresName: polsek.polres.name,
      }))
    ].sort((a, b) => a.name.localeCompare(b.name))

    return NextResponse.json({
      success: true,
      data: locations
    })
  } catch (error) {
    console.error('Error fetching pickup locations:', error)
    return NextResponse.json(
      { 
        success: false, 
        message: 'Gagal mengambil data lokasi pengambilan' 
      },
      { status: 500 }
    )
  }
}