import type { Prisma } from '@prisma/client';

/** Yönetim listeleri ve CSV dışa aktarma aynı filtreleri kullanır. */
export type OrderSP = { q?: string; s?: string; t?: string; p?: string; from?: string; to?: string; o?: string; page?: string };
export type UserSP = { q?: string; f?: string; o?: string; page?: string };
export type PaySP = { q?: string; s?: string; p?: string; from?: string; to?: string; page?: string };

const range = (from?: string, to?: string) => (from || to ? { createdAt: { ...(from ? { gte: new Date(from + 'T00:00:00+03:00') } : {}), ...(to ? { lte: new Date(to + 'T23:59:59+03:00') } : {}) } } : {});
const ci = (q: string) => ({ contains: q, mode: 'insensitive' as const });

export function orderWhere(sp: OrderSP): Prisma.OrderWhereInput {
  const q = sp.q?.trim();
  const ap = q?.match(/^(\d+)\s*[/ ]\s*(\d+)$/); // "101/5" → ada/parsel
  return {
    ...(sp.s ? { status: sp.s as never } : {}),
    ...(sp.t ? { template: sp.t } : {}),
    ...(sp.p ? { plan: sp.p } : {}),
    ...range(sp.from, sp.to),
    ...(q ? { OR: ap ? [{ ada: ap[1], parsel: ap[2] }] : [
      { code: ci(q) }, { user: { email: ci(q) } }, { mahalle: ci(q) }, { ilce: ci(q) }, { il: ci(q) }, { contactName: ci(q) }, { id: q },
    ] } : {}),
  };
}
export const ORDER_SORT: Record<string, Prisma.OrderOrderByWithRelationInput> = { yeni: { createdAt: 'desc' }, eski: { createdAt: 'asc' }, guncel: { updatedAt: 'desc' } };

export function userWhere(sp: UserSP): Prisma.UserWhereInput {
  const q = sp.q?.trim();
  const f: Prisma.UserWhereInput =
    sp.f === 'admin' ? { role: 'ADMIN' } : sp.f === 'dogrulanmamis' ? { emailVerifiedAt: null } : sp.f === 'kredili' ? { credits: { gt: 0 } }
      : sp.f === 'askida' ? { disabledAt: { not: null } } : sp.f === 'odeyen' ? { payments: { some: { status: 'succeeded', plan: { not: 'admin' } } } }
        : sp.f === 'davetli' ? { referredById: { not: null } } : {};
  return { ...f, ...(q ? { OR: [{ email: ci(q) }, { name: ci(q) }, { company: ci(q) }, { phone: ci(q) }, { refCode: q.toUpperCase() }, { id: q }] } : {}) };
}
export const USER_SORT: Record<string, Prisma.UserOrderByWithRelationInput> = { yeni: { createdAt: 'desc' }, eski: { createdAt: 'asc' }, kredi: { credits: 'desc' }, siparis: { orders: { _count: 'desc' } } };

export function paymentWhere(sp: PaySP): Prisma.PaymentWhereInput {
  const q = sp.q?.trim();
  return {
    ...(sp.s ? { status: sp.s } : {}),
    ...(sp.p ? { plan: sp.p } : {}),
    ...range(sp.from, sp.to),
    ...(q ? { OR: [{ user: { email: ci(q) } }, { dodoPaymentId: q }, { dodoSessionId: q }, { order: { code: ci(q) } }, { id: q }] } : {}),
  };
}
