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

export class DistrictRepository {
  async create(data: Prisma.DistrictUncheckedCreateInput) {
    return prisma.district.create({ data });
  }

  async findAll(skip?: number, take?: number, search?: string, status?: boolean, stateId?: bigint) {
    const where: Prisma.DistrictWhereInput = {};

    if (search) {
      where.OR = [
        { name: { contains: search } },
        { tamilName: { contains: search } },
      ];
    }

    if (status !== undefined) {
      where.status = status;
    }

    if (stateId !== undefined) {
      where.stateId = stateId;
    }

    const [items, total] = await Promise.all([
      prisma.district.findMany({
        where,
        ...(skip !== undefined ? { skip } : {}),
        ...(take !== undefined ? { take } : {}),
        orderBy: { id: 'desc' },
        include: { state: true },
      }),
      prisma.district.count({ where }),
    ]);

    return { items, total };
  }

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

  async findByName(name: string, excludeId?: bigint) {
    return prisma.district.findFirst({
      where: {
        name: {
          equals: name.trim(),
        },
        ...(excludeId ? { id: { not: excludeId } } : {}),
      },
    });
  }

  async findByTamilName(tamilName: string, excludeId?: bigint) {
    return prisma.district.findFirst({
      where: {
        tamilName: {
          equals: tamilName.trim(),
        },
        ...(excludeId ? { id: { not: excludeId } } : {}),
      },
    });
  }

  async update(id: bigint, data: Prisma.DistrictUncheckedUpdateInput) {
    return prisma.district.update({ where: { id }, data });
  }

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