import { Prisma } from "../../src/generated/prisma/client.js";
import prisma from "../config/prisma.js";

export class FastBillingRepository {
  async create(data: Prisma.FastBillingCreateInput) {
    return prisma.fastBilling.create({ 
      data,
      include: { items: true } 
    });
  }

  async findAll(skip?: number, take?: number, startDate?: Date, endDate?: Date, search?: string) {
    const where: Prisma.FastBillingWhereInput = {};

    if (startDate && endDate) {
      where.billDate = {
        gte: startDate,
        lte: endDate,
      };
    } else if (startDate) {
      where.billDate = { gte: startDate };
    } else if (endDate) {
      where.billDate = { lte: endDate };
    }

    if (search) {
      where.OR = [
        { customerName: { contains: search } },
        { billNo: { contains: search } },
        { items: { some: { vegetableName: { contains: search } } } },
      ];
    }

    const queryArgs: any = {
      where,
      skip,
      include: { items: true },
      orderBy: { createdAt: "desc" },
    };
    if (take !== undefined) queryArgs.take = take;

    const items = await prisma.fastBilling.findMany(queryArgs);

    const total = await prisma.fastBilling.count({ where });

    return { items, total };
  }

  async findById(id: bigint) {
    return prisma.fastBilling.findUnique({ 
      where: { id },
      include: { items: true }
    });
  }

  async update(id: bigint, data: Prisma.FastBillingUpdateInput) {
    return prisma.fastBilling.update({ 
      where: { id }, 
      data,
      include: { items: true }
    });
  }

  async delete(id: bigint) {
    return prisma.fastBilling.delete({ where: { id } });
  }

  async generateBillNo() {
    const count = await prisma.fastBilling.count();
    return `FB-${String(count + 1).padStart(5, '0')}`;
  }
}
