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

export async function POST(req: Request) {
  try {
    const auth = await requireAuth(req);
    const canModerate = auth.role === Role.ADMIN || auth.role === Role.LISTING_MODERATOR;
    if (!canModerate) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await req.json();
    const listingId = String(body.listingId ?? '');
    const action = body.action ?? 'approve';
    const reason = body.reason ? String(body.reason).slice(0, 500) : null;
    if (!listingId) {
      return NextResponse.json({ error: 'listingId is required' }, { status: 400 });
    }

    let status: ListingStatus;
    if (action === 'reject') status = ListingStatus.REJECTED;
    else if (action === 'remove') status = ListingStatus.REMOVED;
    else if (action === 'publish' || action === 'approve') status = ListingStatus.PUBLISHED;
    else status = ListingStatus.PENDING;

    const updated = await prisma.listing.update({
      where: { id: listingId },
      data: {
        status,
        published: status === ListingStatus.PUBLISHED,
        approvedAt: status === ListingStatus.PUBLISHED ? new Date() : null,
        approvedById: status === ListingStatus.PUBLISHED ? auth.userId : null,
        rejectedAt: status === ListingStatus.REJECTED ? new Date() : null,
        rejectedById: status === ListingStatus.REJECTED ? auth.userId : null,
        rejectedReason: status === ListingStatus.REJECTED ? reason : null,
        removedAt: status === ListingStatus.REMOVED ? new Date() : null,
        removedById: status === ListingStatus.REMOVED ? auth.userId : null,
        removedReason: status === ListingStatus.REMOVED ? reason : null,
      },
      select: { id: true, status: true, approvedAt: true, approvedById: true },
    });

    return NextResponse.json({ ok: true, listing: updated });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Admin listing approval error', error);
    return NextResponse.json({ error: 'Approval failed' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
