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

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

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

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

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

// PUT update Polres
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  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 exists
    const existingPolres = await db.polres.findUnique({
      where: { id: params.id }
    });

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

    // Check if name is being changed and if it conflicts with existing Polres
    if (name !== existingPolres.name) {
      const nameConflict = await db.polres.findUnique({
        where: { name }
      });

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

    // Update Polres
    const updatedPolres = await db.polres.update({
      where: { id: params.id },
      data: {
        name,
        address,
        phone,
        email,
        website,
        fax,
        description,
        logo,
        photo,
        kapolresName,
        kapolresNRP,
        kapolresPangkat
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Polres berhasil diperbarui',
      data: updatedPolres
    });
  } catch (error) {
    console.error('Error updating Polres:', error);
    return NextResponse.json(
      { success: false, message: 'Terjadi kesalahan saat memperbarui Polres' },
      { status: 500 }
    );
  }
}

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

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

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

    // Soft delete Polres (set isActive to false)
    await db.polres.update({
      where: { id: params.id },
      data: { isActive: false }
    });

    // Also soft delete all related Polseks
    await db.polsek.updateMany({
      where: { polresId: params.id },
      data: { isActive: false }
    });

    return NextResponse.json({
      success: true,
      message: 'Polres dan semua Polsek terkait berhasil dihapus'
    });
  } catch (error) {
    console.error('Error deleting Polres:', error);
    return NextResponse.json(
      { success: false, message: 'Terjadi kesalahan saat menghapus Polres' },
      { status: 500 }
    );
  }
}