import type { Admin } from '../../admin/entities/admin.entity';
import type { Restaurant } from '../../restaurants/entities/restaurant.entity';

export interface AdminLoginResponse {
  id: string;
  firstName?: string;
  lastName?: string;
  phone: string;
  role: string;
  permissions: string[];
  restaurant?: {
    id: string;
    name: string;
    slug: string;
  };
}

export class AdminLoginTransformer {
  static async transform(admin: Admin, restaurant?: Restaurant): Promise<AdminLoginResponse> {
    // Find the AdminRole that matches the restaurant (or get the first one)
    let adminRole = admin.roles.getItems().find(r => (restaurant ? r.restaurant?.id === restaurant.id : true));

    // If no match found, get the first one
    if (!adminRole && admin.roles.getItems().length > 0) {
      adminRole = admin.roles.getItems()[0];
    }

    if (!adminRole) {
      return {
        id: admin.id,
        firstName: admin.firstName,
        lastName: admin.lastName,
        phone: admin.phone,
        role: '',
        permissions: [],
        restaurant: restaurant
          ? {
              id: restaurant.id,
              name: restaurant.name,
              slug: restaurant.slug,
            }
          : undefined,
      };
    }

    // Get the role from AdminRole
    const role = adminRole.role;
    if (!role) {
      return {
        id: admin.id,
        firstName: admin.firstName,
        lastName: admin.lastName,
        phone: admin.phone,
        role: '',
        permissions: [],
        restaurant: restaurant
          ? {
              id: restaurant.id,
              name: restaurant.name,
              slug: restaurant.slug,
            }
          : undefined,
      };
    }

    // Extract permissions - ensure collection is loaded if needed
    let permissions: string[] = [];
    if (role.permissions) {
      if (role.permissions.isInitialized()) {
        permissions = role.permissions.getItems().map(p => p.name);
      } else {
        await role.permissions.loadItems();
        permissions = role.permissions.getItems().map(p => p.name);
      }
    }

    return {
      id: admin.id,
      firstName: admin.firstName,
      lastName: admin.lastName,
      phone: admin.phone,
      role: role.name,
      permissions,
      restaurant: restaurant
        ? {
            id: restaurant.id,
            name: restaurant.name,
            slug: restaurant.slug,
          }
        : undefined,
    };
  }
}
