import chronicleInstance from "@/shared/services/chronicleInstance";
import { bufferContentValidator, securityLogger } from "@/shared/services/validation";
import { presignedAxios } from "@/shared/services/presignedAxios";

export const MessageService = {
  async uploadImage(file: File, uploadUrl: string) {
    if (!uploadUrl) throw new Error("Upload URL is undefined.");

    // Validate file buffer against declared MIME type
    const validationResult = await bufferContentValidator.validateMimeType(
      new Uint8Array(await file.slice(0, 512).arrayBuffer()) as any,
      file.type
    );

    if (!validationResult.isValid) {
      // Log validation failure
      await securityLogger.logValidationEvent({
        timestamp: new Date(),
        fileSize: file.size,
        fileName: file.name,
        declaredMime: file.type,
        detectedMime: validationResult.detectedMime,
        validationResult: 'mismatch',
        errorDetails: validationResult.error,
        module: 'user-management',
        endpoint: '/staff/upload',
      });

      throw new Error(validationResult.error || 'File validation failed');
    }

    // Check if MIME type is allowed (images only)
    const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
    if (!bufferContentValidator.isAllowedMimeType(file.type, allowedMimeTypes)) {
      await securityLogger.logValidationEvent({
        timestamp: new Date(),
        fileSize: file.size,
        fileName: file.name,
        declaredMime: file.type,
        detectedMime: validationResult.detectedMime,
        validationResult: 'error',
        errorDetails: `File type ${file.type} is not allowed. Only images are allowed.`,
        module: 'user-management',
        endpoint: '/staff/upload',
      });

      throw new Error(`File type ${file.type} is not allowed. Only images are allowed.`);
    }

    // Log validation success
    await securityLogger.logValidationEvent({
      timestamp: new Date(),
      fileSize: file.size,
      fileName: file.name,
      declaredMime: file.type,
      detectedMime: validationResult.detectedMime,
      validationResult: 'success',
      module: 'user-management',
      endpoint: '/staff/upload',
    });

    return presignedAxios.put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    });
  },

  async updateUploadStatus(
    id: string,
    uploadedSuccessfully: boolean
  ): Promise<void> {
    await chronicleInstance.patch(
      `/staff/${id}/upload-status`,
      { uploadedSuccessfully },
      {
        headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
      }
    );
  },

  // Stub methods for incomplete branch - these should be implemented in the main branch
  async getItem(id: string): Promise<any> {
    throw new Error('Not implemented in this branch');
  },

  async getItems(params: any): Promise<any> {
    throw new Error('Not implemented in this branch');
  },

  async createItem(payload: any): Promise<any> {
    throw new Error('Not implemented in this branch');
  },

  async updateItem(id: string, data: any): Promise<any> {
    throw new Error('Not implemented in this branch');
  },

  async deleteItem(id: string): Promise<void> {
    throw new Error('Not implemented in this branch');
  },
};
