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 shopType = searchParams.get('shopType');
    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.ShopWhereInput = {
      isAvailable: true,
    };

    if (division) where.division = division;
    if (shopType) where.shopType = shopType;
    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 [shops, total] = await Promise.all([
      db.shop.findMany({
        where,
        include: {
          owner: {
            select: { id: true, name: true, phone: true, avatar: true },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      db.shop.count({ where }),
    ]);

    return NextResponse.json({
      shops,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Shops 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,
      shopType,
      area,
      images,
      address,
      division,
      district,
      upazila,
      latitude,
      longitude,
      ownerId,
    } = body;

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

    const shop = await db.shop.create({
      data: {
        title,
        description,
        price: parseFloat(String(price)),
        shopType: shopType || 'commercial',
        area: area ? parseFloat(String(area)) : null,
        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({ shop }, { status: 201 });
  } catch (error) {
    console.error('Shops 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, shopType, area, images, address, division, district, upazila, latitude, longitude } = body;

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

    const existingShop = await db.shop.findUnique({ where: { id } });
    if (!existingShop) {
      return NextResponse.json(
        { error: 'Shop not found' },
        { status: 404 }
      );
    }

    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 (shopType) updateData.shopType = shopType;
    if (area !== undefined) updateData.area = area ? parseFloat(String(area)) : null;
    if (images !== undefined) updateData.images = images ? JSON.stringify(images) : '[]';
    if (address) updateData.address = address;
    if (division) updateData.division = division;
    if (district) updateData.district = district;
    if (upazila !== undefined) updateData.upazila = upazila;
    if (latitude !== undefined) updateData.latitude = latitude ? parseFloat(String(latitude)) : null;
    if (longitude !== undefined) updateData.longitude = longitude ? parseFloat(String(longitude)) : null;

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

    return NextResponse.json({ shop });
  } catch (error) {
    console.error('Shops 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: 'Shop ID is required' },
        { status: 400 }
      );
    }

    const existingShop = await db.shop.findUnique({ where: { id } });
    if (!existingShop) {
      return NextResponse.json(
        { error: 'Shop not found' },
        { status: 404 }
      );
    }

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

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