import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { Admin } from '../entities/admin.entity';
import { AdminRole } from '../entities/adminRole.entity';
import { RestRepository } from '../../restaurants/repositories/rest.repository';
import { Injectable } from '@nestjs/common';
import { normalizePhone } from '../../utils/phone.util';

@Injectable()
export class AdminRepository extends EntityRepository<Admin> {
  constructor(
    readonly em: EntityManager,
    private readonly restRepository: RestRepository,
  ) {
    super(em, Admin);
  }

  async findByPhoneAndRestaurantSlug(phone: string, slug: string): Promise<Admin | null> {
     const normalizedPhone = normalizePhone(phone);
    // First, find the restaurant by slug using the same repository as auth service
    const restaurant = await this.restRepository.findOne({ slug });
    if (!restaurant) {
      return null;
    }

    // Find AdminRole that matches the admin phone and restaurant
    const adminRole = await this.em.findOne(
      AdminRole,
      {
        admin: { phone: normalizedPhone },
        restaurant: { id: restaurant.id },
      },
      { populate: ['admin', 'admin.roles', 'role', 'role.permissions', 'restaurant'] },
    );

    if (!adminRole || !adminRole.admin) {
      return null;
    }

    // Ensure all roles are populated
    await adminRole.admin.roles.loadItems();
    for (const role of adminRole.admin.roles.getItems()) {
      if (role.role && role.role.permissions && !role.role.permissions.isInitialized()) {
        await role.role.permissions.loadItems();
      }
    }

    return adminRole.admin;
  }
  async findAdminsWithPermission(restaurantId: string, permission: string): Promise<Admin[]> {
    const admins = await this.em.find(
      Admin,
      { roles: { restaurant: { id: restaurantId }, role: { permissions: { name: permission } } } },
      { populate: ['roles', 'roles.role', 'roles.role.permissions'] },
    );
    return admins;
  }
}
