// user.service.ts - COMPLETE FIXED VERSION
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '@environments/environment';

export interface UserDocument {
    filename: string;
    path: string;
    uploaded_at: string;
    document_type: string;
    document_type_other?: string;
}

export interface User {
    id?: number;
    user_id?: string;
    username: string;
    email: string;
    contact: string;
    roles: string;
    user_status: string;
    password?: string;
    photo?: string;
    company_logo?: string;
    documents?: UserDocument[];
    created_at?: string;
    updated_at?: string;
    machines?: any[];
}

export interface DocumentWithMetadata {
    file: File;
    documentType: string;
    documentTypeOther?: string;
}

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private BaseUrl = environment.apiUrl1;
  private backendBaseUrl = environment.apiUrl; // Base URL without /users

  constructor(private http: HttpClient) { }

  /**
   * CRITICAL FIX: Convert relative file paths to full URLs
   * This ensures files are loaded from the backend server (localhost:5000)
   * instead of the Angular dev server (localhost:4200)
   */
  getFullFileUrl(path: string | undefined | null): string | null {
    if (!path) return null;
    
    // If path already starts with http, return as-is
    if (path.startsWith('http://') || path.startsWith('https://')) {
      return path;
    }
    
    // If path starts with /, prepend backend base URL
    if (path.startsWith('/')) {
      return this.backendBaseUrl + path;
    }
    
    // Otherwise, prepend backend base URL with /
    return this.backendBaseUrl + '/' + path;
  }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.BaseUrl);
  }

  addUser(
    user: Partial<User>,
    photoFile?: File,
    logoFile?: File,
    documentFiles?: DocumentWithMetadata[]
  ): Observable<User> {
    const formData = this.createFormData(user, photoFile, logoFile, documentFiles);
    return this.http.post<User>(this.BaseUrl, formData);
  }

  updateUser(
    id: number,
    user: Partial<User>,
    photoFile?: File,
    logoFile?: File,
    documentFiles?: DocumentWithMetadata[]
  ): Observable<User> {
    const url = `${this.BaseUrl}/${id}`;
    const formData = this.createFormData(user, photoFile, logoFile, documentFiles);
    console.log('PUT Request URL:', url);
    return this.http.put<User>(url, formData);
  }

  deleteUser(id: number): Observable<any> {
    const url = `${this.BaseUrl}/${id}`;
    console.log('Deleting user:', url);
    return this.http.delete(url);
  }

  deleteUserDocument(userId: number, documentPath: string): Observable<any> {
    // Clean the path - remove /uploads/ prefix if present
    const cleanPath = documentPath.replace(/^\/uploads\//, '');
    const url = `${this.BaseUrl}/${userId}/documents/${cleanPath}`;
    console.log('Deleting document:', url);
    return this.http.delete(url);
  }

  private createFormData(
    user: Partial<User>,
    photoFile?: File,
    logoFile?: File,
    documentFiles?: DocumentWithMetadata[]
  ): FormData {
    const formData = new FormData();

    // Append user data
    if (user.username) formData.append('username', user.username);
    if (user.email) formData.append('email', user.email);
    if (user.contact) formData.append('contact', user.contact);
    if (user.roles) formData.append('roles', user.roles);
    if (user.user_status) formData.append('user_status', user.user_status);
    if (user.password) formData.append('password', user.password);

    // Append photo file
    if (photoFile) {
      formData.append('photo', photoFile, photoFile.name);
    }

    // Append logo file
    if (logoFile) {
      formData.append('company_logo', logoFile, logoFile.name);
    }

    // Append documents with metadata
    if (documentFiles && documentFiles.length > 0) {
      const documentsMetadata = documentFiles.map(doc => ({
        filename: doc.file.name,
        document_type: doc.documentType,
        document_type_other: doc.documentTypeOther || ''
      }));
      
      formData.append('documents_metadata', JSON.stringify(documentsMetadata));
      
      documentFiles.forEach(doc => {
        formData.append('documents', doc.file, doc.file.name);
      });
    }

    return formData;
  }

  // Validation helpers
  validateFile(file: File, maxSizeMB: number = 10): string | null {
    const maxSizeBytes = maxSizeMB * 1024 * 1024;
    if (file.size > maxSizeBytes) {
      return `File size exceeds ${maxSizeMB}MB limit`;
    }
    return null;
  }

  isValidImageType(file: File): boolean {
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    return validTypes.includes(file.type);
  }

  isValidDocumentType(file: File): boolean {
    const validTypes = [
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'image/jpeg',
      'image/jpg',
      'image/png'
    ];
    return validTypes.includes(file.type);
  }

  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  }
}