import { GET } from '@/app/api/fetchImage/route';
import { NextRequest } from 'next/server';
import { mockFetch } from '@/app/__tests__/__mocks__/mock-fetch-img';

jest.mock('next/server', () => {
  class NextResponseClass {
    body: unknown;
    init: unknown;
    constructor(body: unknown, init?: unknown) {
      this.body = body;
      this.init = init;
    }
    static json(body: unknown, init?: unknown) {
      return new NextResponseClass(body, init);
    }
    static from(body: unknown, init?: unknown) {
      return new NextResponseClass(body, init);
    }
  }
  return { NextResponse: NextResponseClass };
});

global.fetch = mockFetch({
  ok: true,
  headers: {
    get: jest.fn().mockReturnValue('image/jpeg'),
  },
  arrayBuffer: jest.fn().mockResolvedValue(new ArrayBuffer(8)),
});

describe('GET /api/fetchImage', () => {
  it('should return an error if no image URL is provided', async () => {
    const mockRequest = {
      url: 'http://localhost/api/fetchImage',
    } as unknown as NextRequest;

    const response = await GET(mockRequest);

    expect(response.body).toEqual({ error: 'Missing URL parameter' });
    expect(response.status).toBe(400);
  });

  it('should fetch an image if URL is provided', async () => {
    const mockRequest = {
      url: 'http://localhost/api/fetchImage?url=https://example.com/image.jpg',
    } as unknown as NextRequest;

    const response = await GET(mockRequest);

    expect(response.body).toBeDefined();
    expect(response.headers.get('Content-Type')).toBe('image/jpeg');
  });
});