import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { isValidId, isValidListingType, sanitizeString } from '@/lib/validation';

export async function GET(request: NextRequest) {
  try {
    // Auth check - any admin can view listings
    const authResult = await verifyAdminPermission(request, 'canManageHouses');
    if ('error' in authResult) return authResult.error;

    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') || 'houses';

    if (!isValidListingType(type)) {
      return NextResponse.json(
        { success: false, error: 'Invalid listing type. Must be: houses, shops, or products' },
        { status: 400 }
      );
    }

    let items: Record<string, unknown>[] = [];

    switch (type) {
      case 'houses':
        items = await db.house.findMany({
          orderBy: { createdAt: 'desc' },
          include: { owner: { select: { name: true, email: true } } },
        });
        break;
      case 'shops':
        items = await db.shop.findMany({
          orderBy: { createdAt: 'desc' },
          include: { owner: { select: { name: true, email: true } } },
        });
        break;
      case 'products':
        items = await db.product.findMany({
          orderBy: { createdAt: 'desc' },
          include: { seller: { select: { name: true, email: true } } },
        });
        break;
    }

    return NextResponse.json({ success: true, items });
  } catch (error) {
    console.error('Admin listings fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch listings' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageHouses');
    if ('error' in authResult) return authResult.error;

    const { id, type, isAvailable } = await request.json();

    if (!id || !type) {
      return NextResponse.json(
        { success: false, error: 'ID and type are required' },
        { status: 400 }
      );
    }

    if (!isValidId(id)) {
      return NextResponse.json(
        { success: false, error: 'Invalid ID format' },
        { status: 400 }
      );
    }

    if (!isValidListingType(type)) {
      return NextResponse.json(
        { success: false, error: 'Invalid listing type' },
        { status: 400 }
      );
    }

    if (typeof isAvailable !== 'boolean') {
      return NextResponse.json(
        { success: false, error: 'isAvailable must be a boolean' },
        { status: 400 }
      );
    }

    let item;
    switch (type) {
      case 'houses':
        item = await db.house.update({ where: { id }, data: { isAvailable } });
        break;
      case 'shops':
        item = await db.shop.update({ where: { id }, data: { isAvailable } });
        break;
      case 'products':
        item = await db.product.update({ where: { id }, data: { isAvailable } });
        break;
      default:
        return NextResponse.json(
          { success: false, error: 'Invalid listing type' },
          { status: 400 }
        );
    }

    return NextResponse.json({ success: true, item });
  } catch (error) {
    console.error('Admin listing update error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update listing' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageHouses');
    if ('error' in authResult) return authResult.error;

    const { id, type } = await request.json();

    if (!id || !type) {
      return NextResponse.json(
        { success: false, error: 'ID and type are required' },
        { status: 400 }
      );
    }

    if (!isValidId(id)) {
      return NextResponse.json(
        { success: false, error: 'Invalid ID format' },
        { status: 400 }
      );
    }

    if (!isValidListingType(type)) {
      return NextResponse.json(
        { success: false, error: 'Invalid listing type' },
        { status: 400 }
      );
    }

    switch (type) {
      case 'houses':
        await db.house.delete({ where: { id } });
        break;
      case 'shops':
        await db.shop.delete({ where: { id } });
        break;
      case 'products':
        await db.product.delete({ where: { id } });
        break;
      default:
        return NextResponse.json(
          { success: false, error: 'Invalid listing type' },
          { status: 400 }
        );
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Admin listing delete error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete listing' },
      { status: 500 }
    );
  }
}
