import {
  CreateUserDto,
  DocumentPayloadDto,
  DocumentResponseDto,
} from "@/shared/dto/External-Portal/External-PortalDto";
import { docuemntUpload, getMyUploads, registerExternalUser, UpdateMyUpload, UpdateMyUploadStatus } from "../services/portalOutgoingService";
import { useState } from "react";
import { nonSmartOfficeFileService } from "@/record-management/services/api/nonSmartOfficeFileService";
import { useQuery } from "@tanstack/react-query";

type documentProps = {
  userId?:string ;
}



export const useDocumentUploads = () => {
  const [isRegistering, setIsRegistering] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);

 const uploadDocuments = async (payload: DocumentPayloadDto, file: File) => {
   let uploadId: string | null = null;
   try {
     // Step 1: Get presigned URL
     const uploadRes = await docuemntUpload(payload);
     const { presigned, id } = uploadRes.data;

     if (!id || !presigned) {
       throw new Error("Failed to get upload URL");
     }

     uploadId = id;

     // Step 2: Upload file to S3 using presigned URL
     await nonSmartOfficeFileService.uploadFile(file, presigned);

     // Step 3: Update upload status to success
     await UpdateMyUploadStatus(id, true);

     return uploadRes.data;
   } catch (error) {
     // If upload failed, mark status as false
     if (uploadId) {
       try {
         await UpdateMyUploadStatus(uploadId, false);
       } catch (statusError) {
         console.error("Failed to update upload status:", statusError);
       }
     }
     throw error;
   }
 };

 const updateDocuemnts = async (Id:string, values:DocumentPayloadDto,file:File) => {
   let uploadId: string | null = null;
   try {
     const uploadRes = await UpdateMyUpload(Id, values);
     const { presigned, id } = uploadRes.data;
     if (!id || !presigned) {
       return Promise.reject(new Error("Failed to Upload Document"));
     }

     uploadId = id;

     await nonSmartOfficeFileService.uploadFile(file, presigned);

     // Update upload status to success
     await UpdateMyUploadStatus(id, true);
     setIsUpdating(true);
     return uploadRes.data;
   } catch (error) {
     // If upload failed, mark status as false
     if (uploadId) {
       try {
         await UpdateMyUploadStatus(uploadId, false);
       } catch (statusError) {
         console.error("Failed to update upload status:", statusError);
       }
     }
     setIsUpdating(false);
     throw error;
   }
 };




  return {
    uploadDocuments,
    isRegistering,
    isUpdating,
    updateDocuemnts,
  
  };
};
