import { PrismaClient, User } from '@prisma/client';

import { BaseRepository } from '../modules/common/repository';

/**
 * EN: User repository for database operations
 * VI: Repository người dùng cho các thao tác database
 */
export class UserRepository extends BaseRepository<User, any, any> {
  constructor(prisma: PrismaClient) {
    super(prisma, 'user');
  }

  /**
   * EN: Find user by email
   * VI: Tìm người dùng theo email
   */
  async findByEmail(email: string): Promise<User | null> {
    return this.prisma.user.findUnique({
      where: { email },
      include: {
        userRoles: {
          include: { role: true },
        },
        userPermissions: {
          include: { permission: true },
        },
      },
    });
  }

  /**
   * EN: Find user by username
   * VI: Tìm người dùng theo username
   */
  async findByUsername(username: string): Promise<User | null> {
    return this.prisma.user.findUnique({
      where: { username },
    });
  }

  /**
   * EN: Find user with roles and permissions
   * VI: Tìm người dùng với roles và permissions
   */
  async findWithPermissions(userId: string): Promise<User | null> {
    return this.prisma.user.findUnique({
      where: { id: userId },
      include: {
        userRoles: {
          where: {
            OR: [
              { expiresAt: null },
              { expiresAt: { gte: new Date() } },
            ],
          },
          include: {
            role: {
              include: {
                permissions: {
                  include: { permission: true },
                },
              },
            },
          },
        },
        userPermissions: {
          where: {
            OR: [
              { expiresAt: null },
              { expiresAt: { gte: new Date() } },
            ],
          },
          include: { permission: true },
        },
      },
    });
  }
}
