/**
 * Upload Service Tests
 *
 * Tests for the S3 upload service including presigned URLs,
 * direct uploads, and signed URL generation for private content.
 */

import { vi, type Mocked } from 'vitest';
import api from '../../services/api';
import {
  getPublicImageUrl,
  getPresignedUrl,
  getPresignedUrls,
  uploadToS3,
  confirmUploads,
  uploadFile,
  getSignedUrl,
  PresignedUrlResponse,
} from '../../services/uploadService';

// Mock the api module
vi.mock('../../services/api');

const mockedApi = api as Mocked<typeof api>;

// Mock XMLHttpRequest for uploadToS3 tests
class MockXMLHttpRequest {
  static instances: MockXMLHttpRequest[] = [];

  status = 200;
  readyState = 4;
  responseText = '';
  upload = {
    onprogress: null as ((e: { lengthComputable: boolean; loaded: number; total: number }) => void) | null,
  };
  onload: (() => void) | null = null;
  onerror: (() => void) | null = null;

  private headers: Record<string, string> = {};
  private method = '';
  private url = '';

  constructor() {
    MockXMLHttpRequest.instances.push(this);
  }

  open(method: string, url: string) {
    this.method = method;
    this.url = url;
  }

  setRequestHeader(key: string, value: string) {
    this.headers[key] = value;
  }

  send(_data: unknown) {
    // Use Promise.resolve().then for async behavior in tests
    // This allows promises to resolve without real delays
    Promise.resolve().then(() => {
      if (this.upload.onprogress) {
        this.upload.onprogress({ lengthComputable: true, loaded: 50, total: 100 });
        this.upload.onprogress({ lengthComputable: true, loaded: 100, total: 100 });
      }
      if (this.onload) {
        this.onload();
      }
    });
  }

  getHeaders() {
    return this.headers;
  }

  getMethod() {
    return this.method;
  }

  getUrl() {
    return this.url;
  }

  static reset() {
    MockXMLHttpRequest.instances = [];
  }

  static getLastInstance() {
    return MockXMLHttpRequest.instances[MockXMLHttpRequest.instances.length - 1];
  }
}

// Store original XMLHttpRequest
const originalXMLHttpRequest = global.XMLHttpRequest;

describe('Upload Service', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    MockXMLHttpRequest.reset();
    // Reset environment variables using stubEnv for Vitest
    vi.stubEnv('VITE_S3_BUCKET', 'test-bucket');
    vi.stubEnv('VITE_AWS_REGION', 'us-east-1');
    // Mock XMLHttpRequest globally
    (global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }).XMLHttpRequest = MockXMLHttpRequest;
  });

  afterEach(() => {
    // Restore original XMLHttpRequest
    (global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }).XMLHttpRequest = originalXMLHttpRequest;
  });

  describe('getPublicImageUrl', () => {
    it('should return empty string for null input', () => {
      expect(getPublicImageUrl(null)).toBe('');
    });

    it('should return empty string for undefined input', () => {
      expect(getPublicImageUrl(undefined)).toBe('');
    });

    it('should return empty string for empty string input', () => {
      expect(getPublicImageUrl('')).toBe('');
    });

    it('should return full S3 URL unchanged', () => {
      const fullUrl = 'https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg';
      expect(getPublicImageUrl(fullUrl)).toBe(fullUrl);
    });

    it('should construct S3 URL from key', () => {
      const key = 'items/550e8400-e29b-41d4-a716-446655440000.jpg';
      const expectedUrl = 'https://test-bucket.s3.us-east-1.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg';
      expect(getPublicImageUrl(key)).toBe(expectedUrl);
    });

    it('should handle profiles folder', () => {
      const key = 'profiles/550e8400-e29b-41d4-a716-446655440000.jpg';
      expect(getPublicImageUrl(key)).toContain('profiles/');
    });

    it('should handle forum folder', () => {
      const key = 'forum/550e8400-e29b-41d4-a716-446655440000.jpg';
      expect(getPublicImageUrl(key)).toContain('forum/');
    });
  });

  describe('getPresignedUrl', () => {
    const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
    const mockResponse: PresignedUrlResponse = {
      uploadUrl: 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc',
      key: 'items/550e8400-e29b-41d4-a716-446655440000.jpg',
      stagingKey: null,
      publicUrl: 'https://bucket.s3.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg',
      expiresAt: new Date().toISOString(),
    };

    it('should request presigned URL with correct parameters', async () => {
      mockedApi.post.mockResolvedValue({ data: mockResponse });

      const result = await getPresignedUrl('item', mockFile);

      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
        uploadType: 'item',
        contentType: 'image/jpeg',
        fileName: 'photo.jpg',
        fileSize: mockFile.size,
      });
      expect(result).toEqual(mockResponse);
    });

    it('should handle different upload types', async () => {
      mockedApi.post.mockResolvedValue({ data: mockResponse });

      await getPresignedUrl('profile', mockFile);
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
        uploadType: 'profile',
      }));

      await getPresignedUrl('message', mockFile);
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
        uploadType: 'message',
      }));

      await getPresignedUrl('forum', mockFile);
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
        uploadType: 'forum',
      }));

      await getPresignedUrl('condition-check', mockFile);
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
        uploadType: 'condition-check',
      }));
    });

    it('should propagate API errors', async () => {
      const error = new Error('API error');
      mockedApi.post.mockRejectedValue(error);

      await expect(getPresignedUrl('item', mockFile)).rejects.toThrow('API error');
    });
  });

  describe('getPresignedUrls', () => {
    const mockFiles = [
      new File(['test1'], 'photo1.jpg', { type: 'image/jpeg' }),
      new File(['test2'], 'photo2.png', { type: 'image/png' }),
    ];

    const mockResponses: PresignedUrlResponse[] = [
      {
        uploadUrl: 'https://presigned-url1.s3.amazonaws.com',
        key: 'items/uuid1.jpg',
        stagingKey: null,
        publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid1.jpg',
        expiresAt: new Date().toISOString(),
      },
      {
        uploadUrl: 'https://presigned-url2.s3.amazonaws.com',
        key: 'items/uuid2.png',
        stagingKey: null,
        publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid2.png',
        expiresAt: new Date().toISOString(),
      },
    ];

    it('should request batch presigned URLs', async () => {
      mockedApi.post.mockResolvedValue({ data: { uploads: mockResponses, baseKey: 'base-key' } });

      const result = await getPresignedUrls('item', mockFiles);

      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign-batch', {
        uploadType: 'item',
        files: [
          { contentType: 'image/jpeg', fileName: 'photo1.jpg', fileSize: mockFiles[0].size },
          { contentType: 'image/png', fileName: 'photo2.png', fileSize: mockFiles[1].size },
        ],
      });
      expect(result).toEqual({ uploads: mockResponses, baseKey: 'base-key' });
    });

    it('should handle empty file array', async () => {
      mockedApi.post.mockResolvedValue({ data: { uploads: [], baseKey: undefined } });

      const result = await getPresignedUrls('item', []);

      expect(result).toEqual({ uploads: [], baseKey: undefined });
    });
  });

  describe('uploadToS3', () => {
    const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
    const mockUploadUrl = 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc';

    it('should upload file successfully', async () => {
      await uploadToS3(mockFile, mockUploadUrl);

      const instance = MockXMLHttpRequest.getLastInstance();
      expect(instance.getMethod()).toBe('PUT');
      expect(instance.getUrl()).toBe(mockUploadUrl);
      expect(instance.getHeaders()['Content-Type']).toBe('image/jpeg');
    });

    it('should call onProgress callback during upload', async () => {
      const onProgress = vi.fn();

      await uploadToS3(mockFile, mockUploadUrl, { onProgress });

      // Progress should be called at least once
      expect(onProgress).toHaveBeenCalled();
      // Should receive percentage values
      expect(onProgress).toHaveBeenCalledWith(expect.any(Number));
    });

    it('should export uploadToS3 function with correct signature', () => {
      expect(typeof uploadToS3).toBe('function');
      // Function accepts file, url, and optional options
      expect(uploadToS3.length).toBeGreaterThanOrEqual(2);
    });

    it('should set correct content-type header', async () => {
      const pngFile = new File(['test'], 'image.png', { type: 'image/png' });
      await uploadToS3(pngFile, mockUploadUrl);

      const instance = MockXMLHttpRequest.getLastInstance();
      expect(instance.getHeaders()['Content-Type']).toBe('image/png');
    });
  });

  describe('confirmUploads', () => {
    it('should confirm uploaded keys', async () => {
      const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
      const mockResponse = { confirmed: keys, total: 2 };

      mockedApi.post.mockResolvedValue({ data: mockResponse });

      const result = await confirmUploads(keys);

      expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', { keys });
      expect(result).toEqual(mockResponse);
    });

    it('should handle partial confirmation', async () => {
      const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
      const mockResponse = { confirmed: ['items/uuid1.jpg'], total: 2 };

      mockedApi.post.mockResolvedValue({ data: mockResponse });

      const result = await confirmUploads(keys);

      expect(result.confirmed).toHaveLength(1);
      expect(result.total).toBe(2);
    });
  });

  describe('uploadFile', () => {
    const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
    const presignResponse: PresignedUrlResponse = {
      uploadUrl: 'https://presigned.s3.amazonaws.com/items/uuid.jpg',
      key: 'items/uuid.jpg',
      stagingKey: null,
      publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid.jpg',
      expiresAt: new Date().toISOString(),
    };

    it('should complete full upload flow successfully', async () => {
      // Mock presign response
      mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
      // Mock confirm response
      mockedApi.post.mockResolvedValueOnce({
        data: { confirmed: [presignResponse.key], total: 1 },
      });

      const result = await uploadFile('item', mockFile);

      expect(result).toEqual({
        key: presignResponse.key,
        publicUrl: presignResponse.publicUrl,
      });

      // Verify presign was called
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
        uploadType: 'item',
        contentType: 'image/jpeg',
        fileName: 'photo.jpg',
        fileSize: mockFile.size,
      });

      // Verify confirm was called
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', {
        keys: [presignResponse.key],
      });
    });

    it('should throw error when upload verification fails', async () => {
      mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
      // Mock confirm returning empty confirmed array
      mockedApi.post.mockResolvedValueOnce({
        data: { confirmed: [], total: 1 },
      });

      await expect(uploadFile('item', mockFile)).rejects.toThrow('Upload verification failed');
    });

    it('should pass onProgress to uploadToS3', async () => {
      const onProgress = vi.fn();

      mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
      mockedApi.post.mockResolvedValueOnce({
        data: { confirmed: [presignResponse.key], total: 1 },
      });

      await uploadFile('item', mockFile, { onProgress });

      // onProgress should have been called during XHR upload
      expect(onProgress).toHaveBeenCalled();
    });

    it('should work with different upload types', async () => {
      const messagePresignResponse = {
        ...presignResponse,
        key: 'messages/uuid.jpg',
        publicUrl: null, // Messages are private
      };

      mockedApi.post.mockResolvedValueOnce({ data: messagePresignResponse });
      mockedApi.post.mockResolvedValueOnce({
        data: { confirmed: [messagePresignResponse.key], total: 1 },
      });

      const result = await uploadFile('message', mockFile);

      expect(result.key).toBe('messages/uuid.jpg');
      expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
        uploadType: 'message',
      }));
    });
  });

  // Note: uploadFiles function was removed from uploadService and replaced with uploadImagesWithVariants
  // Tests for batch uploads would need to be updated to test the new function

  describe('getSignedUrl', () => {
    it('should request signed URL for private content', async () => {
      const key = 'messages/uuid.jpg';
      const signedUrl = 'https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc';

      mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });

      const result = await getSignedUrl(key);

      expect(mockedApi.get).toHaveBeenCalledWith(`/upload/signed-url/${encodeURIComponent(key)}`);
      expect(result).toBe(signedUrl);
    });

    it('should encode key in URL', async () => {
      const key = 'condition-checks/uuid with spaces.jpg';
      const signedUrl = 'https://bucket.s3.amazonaws.com/signed';

      mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });

      await getSignedUrl(key);

      expect(mockedApi.get).toHaveBeenCalledWith(
        `/upload/signed-url/${encodeURIComponent(key)}`
      );
    });

    it('should propagate API errors', async () => {
      const error = new Error('Unauthorized');
      mockedApi.get.mockRejectedValue(error);

      await expect(getSignedUrl('messages/uuid.jpg')).rejects.toThrow('Unauthorized');
    });
  });
});
