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

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

    const polresList = await db.polres.findMany({
      where: {
        isActive: true
      },
      orderBy: {
        order: 'asc'
      },
      include: {
        polseks: {
          where: {
            isActive: true
          },
          orderBy: {
            order: 'asc'
          }
        }
      }
    });

    return NextResponse.json({
      success: true,
      data: polresList
    });
  } catch (error) {
    console.error('Error fetching Polres:', error);
    return NextResponse.json(
      { success: false, message: 'Terjadi kesalahan saat mengambil data Polres' },
      { status: 500 }
    );
  }
}

// POST create new Polres
export async function POST(request: NextRequest) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request);
    if (!authResult.success) {
      return NextResponse.json(
        { success: false, message: authResult.message },
        { status: 401 }
      );
    }

    const body = await request.json();
    const {
      name,
      address,
      phone,
      email,
      website,
      fax,
      description,
      logo,
      photo,
      kapolresName,
      kapolresNRP,
      kapolresPangkat
    } = body;

    // Validate required fields
    if (!name || !address) {
      return NextResponse.json(
        { success: false, message: 'Nama dan alamat wajib diisi' },
        { status: 400 }
      );
    }

    // Check if Polres name already exists
    const existingPolres = await db.polres.findUnique({
      where: { name }
    });

    if (existingPolres) {
      return NextResponse.json(
        { success: false, message: 'Polres dengan nama ini sudah ada' },
        { status: 400 }
      );
    }

    // Get the highest order value
    const lastPolres = await db.polres.findFirst({
      orderBy: { order: 'desc' }
    });

    const newOrder = lastPolres ? lastPolres.order + 1 : 1;

    // Create new Polres
    const newPolres = await db.polres.create({
      data: {
        name,
        address,
        phone,
        email,
        website,
        fax,
        description,
        logo,
        photo,
        kapolresName,
        kapolresNRP,
        kapolresPangkat,
        order: newOrder
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Polres berhasil ditambahkan',
      data: newPolres
    });
  } catch (error) {
    console.error('Error creating Polres:', error);
    return NextResponse.json(
      { success: false, message: 'Terjadi kesalahan saat menambahkan Polres' },
      { status: 500 }
    );
  }
}