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

// GET all Polsek
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 { searchParams } = new URL(request.url);
    const polresId = searchParams.get('polresId');

    const polsekList = await db.polsek.findMany({
      where: {
        isActive: true,
        ...(polresId && { polresId })
      },
      orderBy: {
        order: 'asc'
      },
      include: {
        polres: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });

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

// POST create new Polsek
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,
      photo,
      kapolsekName,
      kapolsekNRP,
      kapolsekPangkat,
      polresId
    } = body;

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

    // Check if Polres exists
    const polres = await db.polres.findUnique({
      where: { id: polresId, isActive: true }
    });

    if (!polres) {
      return NextResponse.json(
        { success: false, message: 'Polres tidak ditemukan' },
        { status: 400 }
      );
    }

    // Check if Polsek name already exists in the same Polres
    const existingPolsek = await db.polsek.findFirst({
      where: {
        name,
        polresId,
        isActive: true
      }
    });

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

    // Get the highest order value for this Polres
    const lastPolsek = await db.polsek.findFirst({
      where: { polresId },
      orderBy: { order: 'desc' }
    });

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

    // Create new Polsek
    const newPolsek = await db.polsek.create({
      data: {
        name,
        address,
        phone,
        email,
        website,
        fax,
        description,
        photo,
        kapolsekName,
        kapolsekNRP,
        kapolsekPangkat,
        polresId,
        order: newOrder
      },
      include: {
        polres: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });

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