import { prisma } from '@/lib/db';
import { currentUser } from '@/lib/auth';
import { orderWhere, paymentWhere, userWhere, ORDER_SORT } from '@/lib/adminQuery';
import { templateById } from '@/lib/templates';
import { planById } from '@/lib/plans';
import { STATUS_TR } from '@/lib/orders';
import { csv } from '@/lib/csv';
import { saleSummary } from '@/lib/sale';
export const dynamic = 'force-dynamic';

const MAX = 20_000;
const d = (x?: Date | null) => (x ? x.toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul' }) : '');

export async function GET(req: Request) {
  const u = await currentUser();
  if (!u || u.role !== 'ADMIN') return new Response('Not Found', { status: 404 }); // gizli yönetim yolu: varlığı belli edilmez
  const sp = Object.fromEntries(new URL(req.url).searchParams) as Record<string, string>;
  let rows: (string | number | null | undefined)[][];
  if (sp.type === 'orders') {
    const os = await prisma.order.findMany({ where: orderWhere(sp), orderBy: ORDER_SORT[sp.o || 'yeni'] || ORDER_SORT.yeni, take: MAX, include: { user: { select: { email: true } } } });
    rows = [['Kod', 'Durum', 'Kullanıcı', 'İl', 'İlçe', 'Mahalle', 'Ada', 'Parsel', 'm²', 'Nitelik', 'Satılan', 'Şablon', 'Paket', 'Kalite', 'İletişim', 'Telefon', 'Oluşturma', 'Teslim', 'Hata'],
      ...os.map((o) => [o.code, STATUS_TR[o.status], o.user.email, o.il, o.ilce, o.mahalle, o.ada, o.parsel, o.areaM2 ? Math.round(o.areaM2) : '', o.nitelik, saleSummary(o) || 'Boş arsa / tarla', templateById(o.template).name, planById(o.plan)?.name || o.plan, o.quality, o.contactName, o.contactPhone, d(o.createdAt), d(o.deliveredAt), o.error])];
  } else if (sp.type === 'users') {
    const us = await prisma.user.findMany({ where: userWhere(sp), orderBy: { createdAt: 'desc' }, take: MAX, include: { _count: { select: { orders: true } } } });
    const spent = await prisma.payment.groupBy({ by: ['userId'], where: { userId: { in: us.map((x) => x.id) }, status: 'succeeded', plan: { not: 'admin' } }, _sum: { amount: true } });
    rows = [['E-posta', 'Ad', 'Firma', 'Telefon', 'Rol', 'Doğrulandı', 'Askıda', 'Kredi', 'Sipariş', 'Harcama (TL)', 'Davet kodu', 'Kayıt'],
      ...us.map((x) => [x.email, x.name, x.company, x.phone, x.role, x.emailVerifiedAt ? 'evet' : 'hayır', x.disabledAt ? 'evet' : 'hayır', x.credits, x._count.orders, ((spent.find((s) => s.userId === x.id)?._sum.amount ?? 0) / 100).toFixed(2).replace('.', ','), x.refCode, d(x.createdAt)])];
  } else if (sp.type === 'payments') {
    const ps = await prisma.payment.findMany({ where: paymentWhere(sp), orderBy: { createdAt: 'desc' }, take: MAX, include: { user: { select: { email: true } }, order: { select: { code: true } } } });
    rows = [['Tarih', 'Kullanıcı', 'Paket', 'Kredi', 'Tutar', 'Para birimi', 'Durum', 'Sipariş', 'Dodo ödeme', 'Dodo oturum'],
      ...ps.map((p) => [d(p.createdAt), p.user.email, p.plan === 'admin' ? 'yönetici tanımı' : planById(p.plan)?.name || p.plan, p.credits, (p.amount / 100).toFixed(2).replace('.', ','), p.currency, p.status, p.order?.code, p.dodoPaymentId, p.dodoSessionId])];
  } else return new Response('type: orders | users | payments', { status: 400 });
  const name = `parselstudyo-${sp.type}-${new Date().toISOString().slice(0, 10)}.csv`;
  return new Response(csv(rows), { headers: { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': `attachment; filename="${name}"`, 'Cache-Control': 'no-store' } });
}
