import { NextResponse } from 'next/server';
import { ListingStatus, Role } from '@prisma/client';
import { prisma } from '../../../../lib/prisma';
import { requireAuth } from '../../../../lib/jwt';

export async function POST(req: Request) {
  try {
    const auth = await requireAuth(req);
    const body = await req.json();
    const listingId = String(body.listingId ?? '');
    const reason = body.reason ? String(body.reason).slice(0, 500) : null;

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

    const listing = await prisma.listing.findUnique({
      where: { id: listingId },
      select: { id: true, ownerId: true, status: true },
    });
    if (!listing) {
      return NextResponse.json({ error: 'Listing not found' }, { status: 404 });
    }

    const isOwner = listing.ownerId === auth.userId;
    const canModerate = auth.role === Role.ADMIN;

    if (!isOwner && !canModerate) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    if (listing.status === ListingStatus.REMOVED) {
      return NextResponse.json({ ok: true, listing });
    }

    const updated = await prisma.listing.update({
      where: { id: listingId },
      data: {
        status: ListingStatus.REMOVED,
        published: false,
        removedAt: new Date(),
        removedById: auth.userId,
        removedReason: reason ?? (isOwner ? 'Removed by owner' : null),
      },
      select: { id: true, status: true, removedAt: true, removedReason: true },
    });

    return NextResponse.json({ ok: true, listing: updated });
  } catch (error) {
    console.error('Remove listing error', error);
    return NextResponse.json({ error: 'Failed to remove listing' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
