// client-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 ClientMachine {
  machine_id: string;
  machine_model: string;
  machine_type: string;
  branch_name: string;
  operation_status: string;
  connection_status: string;
}

export interface ClientRefiller {
  id: number;
  user_id: string;
  username: string;
  email: string;
  contact: string;
  assigned_machines_count: number;
  assigned_machines: Array<{
    machine_id: string;
    machine_model: string;
    branch_name: string;
  }>;
}

export interface ClientDetail {
  id: number;
  user_id: string;
  username: string;
  email: string;
  contact: string;
  photo?: string;
  company_logo?: string;
  created_at: string;
  user_status: string;
  
  // Machines owned by this client
  machines: ClientMachine[];
  machines_count: number;
  
  // Refillers assigned to this client
  refillers: ClientRefiller[];
  refillers_count: number;
}

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

  constructor(private http: HttpClient) {}

  /**
   * Get all clients with their machines and refillers
   */
  getClientsWithDetails(): Observable<ClientDetail[]> {
    // First get all users
    return this.http.get<any[]>(`${this.apiUrl}/users`).pipe(
      map(users => {
        // Filter only clients
        const clients = users.filter(u => u.roles === 'Client');
        
        // Also get all machines to map to clients
        return { clients, users };
      }),
      // Now fetch machines
      switchMap(({ clients, users }) => {
        return this.http.get<any[]>(`${this.apiUrl}/machines`).pipe(
          map(machines => {
            // Transform clients with their machines and refillers
            return clients.map(client => 
              this.transformToClientDetail(client, users, machines)
            );
          })
        );
      })
    );
  }

  /**
   * Get single client with details
   */
  getClientById(clientId: number): Observable<ClientDetail> {
    // Fetch client, users, and machines in parallel
    return this.http.get<any>(`${this.apiUrl}/users/${clientId}`).pipe(
      switchMap(client => {
        // Get all users and machines
        return this.http.get<any[]>(`${this.apiUrl}/users`).pipe(
          switchMap(users => {
            return this.http.get<any[]>(`${this.apiUrl}/machines`).pipe(
              map(machines => this.transformToClientDetail(client, users, machines))
            );
          })
        );
      })
    );
  }

  /**
   * Get machines for a specific client
   */
  getClientMachines(clientId: number): Observable<ClientMachine[]> {
    return this.http.get<ClientMachine[]>(`${this.apiUrl}/clients/${clientId}/machines`);
  }

  /**
   * Get refillers assigned to a specific client
   */
  getClientRefillers(clientId: number): Observable<ClientRefiller[]> {
    return this.http.get<ClientRefiller[]>(`${this.apiUrl}/users/${clientId}/assigned-refillers`);
  }

  /**
   * Transform user data to ClientDetail format
   */
  private transformToClientDetail(client: any, allUsers: any[], allMachines: any[]): ClientDetail {
    // Get machines owned by this client (client_id matches)
    const machines: ClientMachine[] = allMachines
      .filter(machine => machine.client_id === client.id)
      .map(machine => ({
        machine_id: machine.machine_id,
        machine_model: machine.machine_model,
        machine_type: machine.machine_type,
        branch_name: machine.branch_name,
        operation_status: machine.operation_status,
        connection_status: machine.connection_status
      }));
    
    // Get refillers assigned to this client
    const refillers = allUsers
      .filter(u => u.roles === 'Refiller' && u.assigned_to === client.id)
      .map(refiller => ({
        id: refiller.id,
        user_id: refiller.user_id,
        username: refiller.username,
        email: refiller.email,
        contact: refiller.contact,
        assigned_machines_count: refiller.assigned_machines_count || 0,
        assigned_machines: refiller.assigned_machines || []
      }));

    return {
      id: client.id,
      user_id: client.user_id,
      username: client.username,
      email: client.email,
      contact: client.contact,
      photo: client.photo,
      company_logo: client.company_logo,
      created_at: client.created_at,
      user_status: client.user_status,
      machines: machines,
      machines_count: machines.length,
      refillers: refillers,
      refillers_count: refillers.length
    };
  }

  /**
   * Get full file URL (same as UserService)
   */
  getFullFileUrl(path: string | undefined | null): string | null {
    if (!path) return null;
    
    if (path.startsWith('http://') || path.startsWith('https://')) {
      return path;
    }
    
    if (path.startsWith('/')) {
      return this.backendBaseUrl + path;
    }
    
    return this.backendBaseUrl + '/' + path;
  }
}