import type { EstimateListFilters } from "@capakraken/shared";
import type { EstimateDbClient } from "./shared.js";

export async function listEstimates(
  db: EstimateDbClient,
  filters: EstimateListFilters = {},
) {
  return db.estimate.findMany({
    where: {
      ...(filters.projectId !== undefined ? { projectId: filters.projectId } : {}),
      ...(filters.status !== undefined ? { status: filters.status } : {}),
      ...(filters.query
        ? {
            OR: [
              { name: { contains: filters.query, mode: "insensitive" } },
              {
                opportunityId: {
                  contains: filters.query,
                  mode: "insensitive",
                },
              },
            ],
          }
        : {}),
    },
    include: {
      project: {
        select: {
          id: true,
          shortCode: true,
          name: true,
          status: true,
        },
      },
      versions: {
        orderBy: { versionNumber: "desc" },
        take: 1,
        select: {
          id: true,
          versionNumber: true,
          label: true,
          status: true,
          updatedAt: true,
        },
      },
    },
    orderBy: { updatedAt: "desc" },
  });
}
