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

export class StateRepository {
  async create(data: Prisma.StateCreateInput) {
    return prisma.state.create({ data });
  }

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

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

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

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

    return { items, total };
  }

  async getActiveList() {
    return prisma.state.findMany({
      where: { status: true },
      select: { id: true, name: true, tamilName: true },
      orderBy: { name: 'asc' },
    });
  }

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

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

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

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

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