import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Order } from "@/models/Order";
import { PriceProposal } from "@/models/PriceProposal";
import { getPayableAmount, getTotalOrderDiscount } from "@/lib/discounts";
import { clientHasInvoices } from "@/lib/accountDeletion";

export async function getClientDetail(clientId: string) {
  await connectDB();
  const client = await Client.findById(clientId).lean();
  if (!client) return null;
  const hasInvoices = await clientHasInvoices(clientId);

  const orders = await Order.find({ clientId })
    .sort({ createdAt: -1 })
    .select("characterOrConcept tag archived rejected createdAt")
    .lean();

  const acceptedProposals = await PriceProposal.find({
    orderId: { $in: orders.map((o) => o._id) },
    status: "accepted",
  }).lean();
  const ordersById = new Map(orders.map((o) => [String(o._id), o]));
  const totalRevenue = acceptedProposals.reduce((sum, p) => {
    const o = ordersById.get(String(p.orderId));
    return sum + getPayableAmount(p.amount, o ? getTotalOrderDiscount(o) : 0);
  }, 0);

  const activeOrdersCount = orders.filter((o) => !o.archived && !o.rejected).length;

  return { client, orders, totalRevenue, activeOrdersCount, hasInvoices };
}
