import { prisma } from '@/lib/prisma';
import { Prisma } from '@/generated/prisma/client';

/**
 * Repository para acceso a datos de Usuarios
 */
export class UserRepository {
  /**
   * Buscar un usuario por ID
   */
  async findById(id: string) {
    return prisma.user.findUnique({
      where: { id },
      include: {
        _count: {
          select: { documents: true },
        },
      },
    });
  }

  /**
   * Buscar un usuario por username
   */
  async findByUsername(username: string) {
    return prisma.user.findUnique({
      where: { username },
    });
  }

  /**
   * Buscar todos los usuarios
   */
  async findMany() {
    return prisma.user.findMany({
      select: {
        id: true,
        name: true,
        username: true,
        role: true,
        createdAt: true,
        updatedAt: true,
        _count: {
          select: {
            documents: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Crear un nuevo usuario
   */
  async create(data: Prisma.UserCreateInput) {
    return prisma.user.create({
      data,
      select: {
        id: true,
        name: true,
        username: true,
        role: true,
        createdAt: true,
        updatedAt: true,
      },
    });
  }

  /**
   * Actualizar un usuario
   */
  async update(id: string, data: Prisma.UserUpdateInput) {
    return prisma.user.update({
      where: { id },
      data,
    });
  }

  /**
   * Eliminar un usuario
   */
  async delete(id: string) {
    return prisma.user.delete({
      where: { id },
    });
  }

  /**
   * Verificar si un usuario existe por username
   */
  async existsByUsername(username: string) {
    const user = await prisma.user.findUnique({
      where: { username },
      select: { id: true },
    });
    return user !== null;
  }

  /**
   * Contar usuarios existentes
   */
  async count() {
    return prisma.user.count();
  }
}

export const userRepository = new UserRepository();
