import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const division = searchParams.get('division');
    const district = searchParams.get('district');
    const rentType = searchParams.get('rentType');
    const roomsMin = searchParams.get('roomsMin');
    const roomsMax = searchParams.get('roomsMax');
    const priceMin = searchParams.get('priceMin');
    const priceMax = searchParams.get('priceMax');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');

    const where: Prisma.HouseWhereInput = {
      isAvailable: true,
    };

    if (division) where.division = division;
    if (district) where.district = district;
    if (rentType) where.rentType = rentType;
    if (roomsMin || roomsMax) {
      where.rooms = {};
      if (roomsMin) where.rooms.gte = parseInt(roomsMin);
      if (roomsMax) where.rooms.lte = parseInt(roomsMax);
    }
    if (priceMin || priceMax) {
      where.price = {};
      if (priceMin) where.price.gte = parseFloat(priceMin);
      if (priceMax) where.price.lte = parseFloat(priceMax);
    }

    const skip = (page - 1) * limit;

    const [houses, total] = await Promise.all([
      db.house.findMany({
        where,
        include: {
          owner: {
            select: { id: true, name: true, phone: true, avatar: true },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      db.house.count({ where }),
    ]);

    return NextResponse.json({
      houses,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Houses GET error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      title,
      description,
      price,
      rooms,
      bathrooms,
      area,
      floor,
      houseType,
      rentType,
      images,
      address,
      division,
      district,
      upazila,
      latitude,
      longitude,
      ownerId,
    } = body;

    if (!title || !description || !price || !rooms || !address || !division || !district || !ownerId) {
      return NextResponse.json(
        { error: 'Missing required fields: title, description, price, rooms, address, division, district, ownerId' },
        { status: 400 }
      );
    }

    const house = await db.house.create({
      data: {
        title,
        description,
        price: parseFloat(String(price)),
        rooms: parseInt(String(rooms)),
        bathrooms: bathrooms ? parseInt(String(bathrooms)) : null,
        area: area ? parseFloat(String(area)) : null,
        floor: floor || null,
        houseType: houseType || 'flat',
        rentType: rentType || 'both',
        images: images ? JSON.stringify(images) : '[]',
        address,
        division,
        district,
        upazila: upazila || null,
        latitude: latitude ? parseFloat(String(latitude)) : null,
        longitude: longitude ? parseFloat(String(longitude)) : null,
        ownerId,
      },
      include: {
        owner: {
          select: { id: true, name: true, phone: true, avatar: true },
        },
      },
    });

    return NextResponse.json({ house }, { status: 201 });
  } catch (error) {
    console.error('Houses POST error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, isAvailable, title, description, price, rooms, bathrooms, area, floor, houseType, rentType, address, division, district, upazila } = body;

    if (!id) {
      return NextResponse.json(
        { error: 'House ID is required' },
        { status: 400 }
      );
    }

    const updateData: Record<string, unknown> = {};
    if (isAvailable !== undefined) updateData.isAvailable = isAvailable;
    if (title) updateData.title = title;
    if (description) updateData.description = description;
    if (price !== undefined) updateData.price = parseFloat(String(price));
    if (rooms !== undefined) updateData.rooms = parseInt(String(rooms));
    if (bathrooms !== undefined) updateData.bathrooms = bathrooms ? parseInt(String(bathrooms)) : null;
    if (area !== undefined) updateData.area = area ? parseFloat(String(area)) : null;
    if (floor !== undefined) updateData.floor = floor;
    if (houseType) updateData.houseType = houseType;
    if (rentType) updateData.rentType = rentType;
    if (address) updateData.address = address;
    if (division) updateData.division = division;
    if (district) updateData.district = district;
    if (upazila !== undefined) updateData.upazila = upazila;

    const house = await db.house.update({
      where: { id },
      data: updateData,
      include: {
        owner: {
          select: { id: true, name: true, phone: true, avatar: true },
        },
      },
    });

    return NextResponse.json({ house });
  } catch (error) {
    console.error('Houses PATCH error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { id } = body;

    if (!id) {
      return NextResponse.json(
        { error: 'House ID is required' },
        { status: 400 }
      );
    }

    await db.house.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Houses DELETE error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
