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

// GET single Polsek
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 polsek = await db.polsek.findUnique({
      where: {
        id: params.id,
        isActive: true
      },
      include: {
        polres: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });

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

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

// PUT update Polsek
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,
      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 Polsek exists
    const existingPolsek = await db.polsek.findUnique({
      where: { id: params.id }
    });

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

    // 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 name is being changed and if it conflicts with existing Polsek in the same Polres
    if (name !== existingPolsek.name || polresId !== existingPolsek.polresId) {
      const nameConflict = await db.polsek.findFirst({
        where: {
          name,
          polresId,
          isActive: true,
          id: { not: params.id }
        }
      });

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

    // Update Polsek
    const updatedPolsek = await db.polsek.update({
      where: { id: params.id },
      data: {
        name,
        address,
        phone,
        email,
        website,
        fax,
        description,
        photo,
        kapolsekName,
        kapolsekNRP,
        kapolsekPangkat,
        polresId
      },
      include: {
        polres: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });

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

// DELETE Polsek
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 Polsek exists
    const existingPolsek = await db.polsek.findUnique({
      where: { id: params.id }
    });

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

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

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