import axios, { AxiosInstance } from 'axios';

export interface DealRoom {
  id: string;
  name: string;
  description?: string;
  status: 'active' | 'archived' | 'closed';
  createdAt: string;
  updatedAt: string;
  participants: string[];
  documents: string[];
}

export interface Document {
  id: string;
  roomId: string;
  fileName: string;
  fileSize: number;
  uploadedBy: string;
  uploadedAt: string;
  category?: string;
  tags?: string[];
}

export class DataroomClient {
  protected client: AxiosInstance;

  constructor(baseURL?: string) {
    const apiBaseURL =
      baseURL ||
      (typeof window !== 'undefined'
        ? process.env.NEXT_PUBLIC_DATAROOM_SERVICE_URL || 'http://localhost:4006'
        : 'http://localhost:4006');

    this.client = axios.create({
      baseURL: apiBaseURL,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // Set up request interceptor for authentication
    this.client.interceptors.request.use(
      (config) => {
        const token = this.getAuthToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );
  }

  private getAuthToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('auth_token');
  }

  setAuthToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem('auth_token', token);
    }
  }

  clearAuthToken(): void {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('auth_token');
    }
  }

  async createDealRoom(data: {
    name: string;
    description?: string;
    participants?: string[];
  }): Promise<DealRoom> {
    const response = await this.client.post<DealRoom>('/api/v1/deal-rooms', data);
    return response.data;
  }

  async getDealRoom(roomId: string): Promise<DealRoom> {
    const response = await this.client.get<DealRoom>(`/api/v1/deal-rooms/${roomId}`);
    return response.data;
  }

  async listDealRooms(filters?: {
    status?: string;
    participantId?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{ rooms: DealRoom[]; total: number }> {
    const response = await this.client.get<{ rooms: DealRoom[]; total: number }>(
      '/api/v1/deal-rooms',
      { params: filters }
    );
    return response.data;
  }

  async updateDealRoom(roomId: string, data: Partial<DealRoom>): Promise<DealRoom> {
    const response = await this.client.patch<DealRoom>(`/api/v1/deal-rooms/${roomId}`, data);
    return response.data;
  }

  async uploadDocument(roomId: string, file: File | Blob, metadata?: {
    category?: string;
    tags?: string[];
  }): Promise<Document> {
    const formData = new FormData();
    formData.append('file', file);
    if (metadata) {
      formData.append('category', metadata.category || '');
      if (metadata.tags) {
        formData.append('tags', JSON.stringify(metadata.tags));
      }
    }

    const response = await this.client.post<Document>(
      `/api/v1/deal-rooms/${roomId}/documents`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );

    return response.data;
  }

  async listDocuments(roomId: string): Promise<Document[]> {
    const response = await this.client.get<Document[]>(
      `/api/v1/deal-rooms/${roomId}/documents`
    );
    return response.data;
  }

  async deleteDocument(roomId: string, documentId: string): Promise<void> {
    await this.client.delete(`/api/v1/deal-rooms/${roomId}/documents/${documentId}`);
  }
}
