import { axiosInstance } from "@/utils/axios";
import { ITransfer } from "../types/transfer";
import { getUserByEmail } from "./user";

interface TransferData {
  transferType: string;
  title?: string;
  message?: string;
  recipientEmail?: string;
  files?: FileData[];
}

interface FileData {
  name: string;
  path: string;
  originalName: string;
  size: number;
  type: string;
  preview?: string;
  serverFileName?: string;
}


interface TransferResponse {
  id: string;
  status: string;
  fileUrls?: { [key: string]: string };
}

const transferApi = {
  
  uploadFile: async (file: File): Promise<string> => {
    try {
      const formData = new FormData();
      formData.append('file', file);
  
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found ');
      }
      const userData = await getUserByEmail(email);
      const userOwner = userData.id;
  
      formData.append('userOwner', userOwner.toString());
  
      const response = await axiosInstance.post('/api/file/upload-personal', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      return response.data;
    } catch (error) {
      console.error('Upload error:', error);
      throw error;
    }
  },

  deleteFile: async (fileName: string): Promise<void> => {
    try {
      await axiosInstance.delete(`/api/file/${fileName}`);
    } catch (error) {
      console.error('Delete error:', error);
      throw error;
    }
  },

  createTransfer: async (data: TransferData): Promise<TransferResponse> => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }
      
      const userData = await getUserByEmail(email);
      const userId = userData.id;

      const transferDataWithUser = {
        ...data,
        userId,
      };

      const response = await axiosInstance.post('/api/file/transfers/add', transferDataWithUser);
      return response.data;
    } catch (error) {
      console.error('Create transfer error:', error);
      throw error;
    }
  },

  getAllTransfers: async (): Promise<ITransfer[]> => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }

      const userData = await getUserByEmail(email);
      const userId = userData.id;

      const response = await axiosInstance.get(`/api/file/transfers/all?userId=${userId}`);
      return response.data;
    } catch (error) {
      console.error('Get transfers error:', error);
      throw error;
    }
  },
  deleteTransfer: async (id: string): Promise<void> => {
    try {
      await axiosInstance.delete(`/api/file/transfers/${id}`);
    } catch (error) {
      console.error('Delete transfer error:', error);
      throw error;
    }
  },
  getTransferUrls: async (transferId: string): Promise<Record<string, string>> => {
    try {
      const response = await axiosInstance.get(`/api/file/transfers/${transferId}/urls`);
      return response.data;
    } catch (error) {
      console.error('Get transfer URLs error:', error);
      throw error;
    }
  },
  

}



export { transferApi };
export type { TransferData, FileData, TransferResponse };