// company-admin-list.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { environment } from 'environments/environment';

export interface AdminDetail {
  id: number;
  user_id: string;
  username: string;
  email: string;
  contact: string;
  roles: string;
  photo?: string;
  company_logo?: string;
  created_at: string;
  updated_at?: string;
  user_status: string;
  created_by?: number;
  created_by_username?: string;
  assigned_to?: number;
  assigned_to_username?: string;
}

@Injectable({
  providedIn: 'root'
})
export class CompanyAdminListService {
  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient) {}

  /**
   * Get all admin users (Management, SuperAdmin, Admin)
   */
  getAdminsWithDetails(): Observable<AdminDetail[]> {
    return this.http.get<any[]>(`${this.apiUrl}/users`).pipe(
      map(users => {
        // Filter only admin roles: Management, SuperAdmin, Admin
        const adminUsers = users.filter(u => 
          u.roles === 'Management' || 
          u.roles === 'SuperAdmin' || 
          u.roles === 'Admin'
        );

        // Transform to AdminDetail format
        return adminUsers.map(admin => this.transformToAdminDetail(admin, users));
      })
    );
  }

  /**
   * Get single admin by ID
   */
  getAdminById(adminId: number): Observable<AdminDetail> {
    return this.http.get<any>(`${this.apiUrl}/users/${adminId}`).pipe(
      switchMap(admin => {
        return this.http.get<any[]>(`${this.apiUrl}/users`).pipe(
          map(users => this.transformToAdminDetail(admin, users))
        );
      })
    );
  }

  /**
   * Transform user data to AdminDetail format
   */
  private transformToAdminDetail(admin: any, allUsers: any[]): AdminDetail {
    // Find who created this admin
    let createdByUsername = 'System';
    if (admin.created_by) {
      const creator = allUsers.find(u => u.id === admin.created_by);
      if (creator) {
        createdByUsername = creator.username;
      }
    }

    // Find who this admin is assigned to (if applicable)
    let assignedToUsername = null;
    if (admin.assigned_to) {
      const assignedUser = allUsers.find(u => u.id === admin.assigned_to);
      if (assignedUser) {
        assignedToUsername = assignedUser.username;
      }
    }

    return {
      id: admin.id,
      user_id: admin.user_id,
      username: admin.username,
      email: admin.email,
      contact: admin.contact,
      roles: admin.roles,
      photo: admin.photo,
      company_logo: admin.company_logo,
      created_at: admin.created_at,
      updated_at: admin.updated_at,
      user_status: admin.user_status,
      created_by: admin.created_by,
      created_by_username: createdByUsername,
      assigned_to: admin.assigned_to,
      assigned_to_username: assignedToUsername
    };
  }

  /**
   * Convert relative file path to full URL
   */
  getFullFileUrl(path: string | undefined): string | null {
    if (!path) return null;
    
    // If already a full URL, return as is
    if (path.startsWith('http://') || path.startsWith('https://')) {
      return path;
    }
    
    // Remove leading slash if present
    const cleanPath = path.startsWith('/') ? path.substring(1) : path;
    
    // Construct full URL
    return `${this.apiUrl}/${cleanPath}`;
  }
}