/**
 * Tests for S3-compatible API Client
 */

import { S3Client } from '../api/client';

// Mock fetch
global.fetch = jest.fn();

function xmlHeaders() {
  return new Map([['content-type', 'application/xml']]);
}

const SINGLE_PAGE_LIST_XML = `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult>
  <Name>my-bucket</Name>
  <Prefix>images/</Prefix>
  <Delimiter>/</Delimiter>
  <IsTruncated>false</IsTruncated>
  <Contents>
    <Key>images/file.jpg</Key>
    <LastModified>2024-01-01T00:00:00.000Z</LastModified>
    <ETag>"abc123"</ETag>
    <Size>1024</Size>
  </Contents>
  <CommonPrefixes>
    <Prefix>images/subfolder/</Prefix>
  </CommonPrefixes>
</ListBucketResult>`;

const TRUNCATED_PAGE_1_XML = `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult>
  <Name>my-bucket</Name>
  <Prefix></Prefix>
  <IsTruncated>true</IsTruncated>
  <NextContinuationToken>token-page-2</NextContinuationToken>
  <Contents>
    <Key>a.jpg</Key>
    <LastModified>2024-01-01T00:00:00.000Z</LastModified>
    <ETag>"a"</ETag>
    <Size>10</Size>
  </Contents>
</ListBucketResult>`;

const TRUNCATED_PAGE_2_XML = `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult>
  <Name>my-bucket</Name>
  <Prefix></Prefix>
  <IsTruncated>false</IsTruncated>
  <Contents>
    <Key>b.jpg</Key>
    <LastModified>2024-01-02T00:00:00.000Z</LastModified>
    <ETag>"b"</ETag>
    <Size>20</Size>
  </Contents>
</ListBucketResult>`;

// Recorded from Neon Object Storage (public_read bucket, path-style). Unlike the
// fixtures above it carries the S3 XML namespace, entity-escaped ETag quotes, and
// both `Marker` and `ContinuationToken` alongside `NextContinuationToken`.
const NEON_PAGE_1_XML = `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>decap-media</Name><Prefix>images/</Prefix><Delimiter>/</Delimiter><MaxKeys>2</MaxKeys><IsTruncated>true</IsTruncated><Marker></Marker><KeyCount>2</KeyCount><NextContinuationToken>aW1hZ2VzL2hlbGxvIHdvcmxkLnR4dA==</NextContinuationToken><CommonPrefixes><Prefix>images/2026/</Prefix></CommonPrefixes><Contents><Key>images/hello world.txt</Key><LastModified>2026-10-21T14:02:07.122Z</LastModified><ETag>&#34;634899aa2ec20b95478704ac150f246e&#34;</ETag><Size>10</Size><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>`;

const NEON_PAGE_2_XML = `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>decap-media</Name><Prefix>images/</Prefix><Delimiter>/</Delimiter><MaxKeys>2</MaxKeys><IsTruncated>false</IsTruncated><Marker></Marker><KeyCount>1</KeyCount><ContinuationToken>aW1hZ2VzL2hlbGxvIHdvcmxkLnR4dA==</ContinuationToken><Contents><Key>images/logo.png</Key><LastModified>2026-10-21T14:02:16.130Z</LastModified><ETag>&#34;7f4f483b50c1592db6e9e73d4fcc14c1&#34;</ETag><Size>2048</Size><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>`;

describe('S3Client', () => {
  const getAccessToken = jest.fn(async () => 'test-access-token');
  const getActiveSiteId = jest.fn(async () => 'test-site-id');

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should initialize with correct parameters', () => {
    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    expect(client).toBeTruthy();
  });

  it('should list objects and parse Contents + CommonPrefixes from XML', async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce({
      ok: true,
      headers: xmlHeaders(),
      text: async () => SINGLE_PAGE_LIST_XML,
    });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const result = await client.listObjects('images/');

    expect(result.isTruncated).toBe(false);
    expect(result.files).toHaveLength(2);

    const folder = result.files.find(f => f.IsDirectory);
    expect(folder).toMatchObject({
      Key: 'images/subfolder/',
      IsDirectory: true,
      ObjectName: 'subfolder',
    });

    const file = result.files.find(f => !f.IsDirectory);
    expect(file).toMatchObject({
      Key: 'images/file.jpg',
      Size: 1024,
      ETag: 'abc123',
      IsDirectory: false,
      ObjectName: 'file.jpg',
    });

    expect(global.fetch).toHaveBeenCalledWith(
      expect.stringContaining('list-type=2'),
      expect.objectContaining({
        method: 'GET',
        headers: expect.objectContaining({
          Authorization: 'Bearer test-access-token',
          'x-site-id': 'test-site-id',
        }),
      }),
    );
  });

  it('should follow pagination via listAllObjects until IsTruncated is false', async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce({
        ok: true,
        headers: xmlHeaders(),
        text: async () => TRUNCATED_PAGE_1_XML,
      })
      .mockResolvedValueOnce({
        ok: true,
        headers: xmlHeaders(),
        text: async () => TRUNCATED_PAGE_2_XML,
      });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const files = await client.listAllObjects('');

    expect(files.map(f => f.Key)).toEqual(['a.jpg', 'b.jpg']);
    expect(global.fetch).toHaveBeenCalledTimes(2);
    expect(global.fetch).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining('continuation-token=token-page-2'),
      expect.anything(),
    );
  });

  it('should parse and paginate a Neon Object Storage listing', async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce({ ok: true, headers: xmlHeaders(), text: async () => NEON_PAGE_1_XML })
      .mockResolvedValueOnce({
        ok: true,
        headers: xmlHeaders(),
        text: async () => NEON_PAGE_2_XML,
      });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const files = await client.listAllObjects('images/');

    expect(files).toEqual([
      {
        Key: 'images/2026/',
        Size: 0,
        LastModified: '',
        ETag: '',
        IsDirectory: true,
        ObjectName: '2026',
      },
      {
        Key: 'images/hello world.txt',
        Size: 10,
        LastModified: '2026-10-21T14:02:07.122Z',
        ETag: '634899aa2ec20b95478704ac150f246e',
        IsDirectory: false,
        ObjectName: 'hello world.txt',
      },
      {
        Key: 'images/logo.png',
        Size: 2048,
        LastModified: '2026-10-21T14:02:16.130Z',
        ETag: '7f4f483b50c1592db6e9e73d4fcc14c1',
        IsDirectory: false,
        ObjectName: 'logo.png',
      },
    ]);
    expect(global.fetch).toHaveBeenCalledTimes(2);
    expect(global.fetch).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining(
        `continuation-token=${encodeURIComponent('aW1hZ2VzL2hlbGxvIHdvcmxkLnR4dA==')}`,
      ),
      expect.anything(),
    );
  });

  it('should build Neon public URLs from the branch endpoint and bucket', () => {
    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const url = client.generatePublicUrl(
      'https://br-cool-darkness-a1b2c3d4.storage.c-1.us-east-2.aws.neon.tech/decap-media',
      'images/hello world.txt',
    );

    expect(url).toBe(
      'https://br-cool-darkness-a1b2c3d4.storage.c-1.us-east-2.aws.neon.tech/decap-media/images/hello%20world.txt',
    );
  });

  it('should handle API errors on list', async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce({
      ok: false,
      status: 403,
      statusText: 'Forbidden',
      headers: { entries: () => [] },
      text: async () => 'Forbidden',
    });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    await expect(client.listObjects('')).rejects.toThrow('S3 API error: 403');
  });

  it('should upload a file with a PUT request', async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce({ ok: true, headers: { entries: () => [] } });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const file = new Blob(['hello'], { type: 'text/plain' });
    await client.uploadFile('images/hello.txt', file);

    expect(global.fetch).toHaveBeenCalledWith(
      'https://edge.example.test/functions/v1/integrations/s3/images/hello.txt',
      expect.objectContaining({ method: 'PUT', body: file }),
    );
  });

  it('should delete a file with a DELETE request', async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce({ ok: true, headers: { entries: () => [] } });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    await client.deleteFile('images/hello.txt');

    expect(global.fetch).toHaveBeenCalledWith(
      'https://edge.example.test/functions/v1/integrations/s3/images/hello.txt',
      expect.objectContaining({ method: 'DELETE' }),
    );
  });

  it('should treat a 404 on delete as success (already gone)', async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce({
      ok: false,
      status: 404,
      headers: { entries: () => [] },
    });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    await expect(client.deleteFile('images/gone.txt')).resolves.toBeUndefined();
  });

  it('should not log response headers when an API call fails', async () => {
    const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
    const secretHeaderValue = 'header-value-that-must-not-be-logged';

    (global.fetch as jest.Mock).mockResolvedValueOnce({
      ok: false,
      status: 500,
      statusText: 'Internal Server Error',
      headers: {
        entries: () => [
          ['x-proxy-internal', secretHeaderValue],
          ['set-cookie', secretHeaderValue],
        ],
      },
      text: async () => 'upstream exploded',
    });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    await expect(client.listObjects('')).rejects.toThrow('S3 API error: 500');

    expect(consoleError).toHaveBeenCalled();
    const logged = JSON.stringify(consoleError.mock.calls);
    expect(logged).not.toContain(secretHeaderValue);
    expect(logged).not.toContain('x-proxy-internal');

    consoleError.mockRestore();
  });

  it('should truncate a long error body before logging it, but not in the thrown error', async () => {
    const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
    const longBody = 'x'.repeat(5000);

    (global.fetch as jest.Mock).mockResolvedValueOnce({
      ok: false,
      status: 500,
      statusText: 'Internal Server Error',
      headers: { entries: () => [] },
      text: async () => longBody,
    });

    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    await expect(client.listObjects('')).rejects.toThrow(longBody);

    const loggedBody = consoleError.mock.calls[0][1].body;
    expect(loggedBody.length).toBeLessThan(longBody.length);
    expect(loggedBody).toContain('(truncated)');

    consoleError.mockRestore();
  });

  it('should generate public URL correctly', () => {
    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const url = client.generatePublicUrl('https://cdn.example.com', 'folder/file.jpg');

    expect(url).toBe('https://cdn.example.com/folder/file.jpg');
  });

  it('should handle URL generation with trailing slash and leading slash key', () => {
    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    const url = client.generatePublicUrl('https://cdn.example.com/', '/folder/file.jpg');

    expect(url).toBe('https://cdn.example.com/folder/file.jpg');
  });

  describe('key encoding', () => {
    const client = new S3Client({
      edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
      getAccessToken,
      getActiveSiteId,
    });

    it.each([
      ['a#b.txt', 'a%23b.txt'],
      ['a?b.txt', 'a%3Fb.txt'],
      ['a%b.txt', 'a%25b.txt'],
      ['a b.txt', 'a%20b.txt'],
      ['folder/a#b.txt', 'folder/a%23b.txt'],
    ])('encodes %s per path segment when building object URLs', async (key, encoded) => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        ok: true,
        headers: { entries: () => [] },
      });

      await client.deleteFile(key);

      expect(global.fetch).toHaveBeenCalledWith(
        `https://edge.example.test/functions/v1/integrations/s3/${encoded}`,
        expect.objectContaining({ method: 'DELETE' }),
      );
    });

    it.each([
      ['a#b.txt', 'a%23b.txt'],
      ['a?b.txt', 'a%3Fb.txt'],
      ['a%b.txt', 'a%25b.txt'],
      ['a b.txt', 'a%20b.txt'],
      ['folder/a#b.txt', 'folder/a%23b.txt'],
    ])('encodes %s per path segment when generating public URLs', (key, encoded) => {
      const url = client.generatePublicUrl('https://cdn.example.com', key);

      expect(url).toBe(`https://cdn.example.com/${encoded}`);
    });
  });

  describe('structured JSON error bodies', () => {
    it('throws the server-provided error message for a JSON error body', async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        ok: false,
        status: 403,
        statusText: 'Forbidden',
        headers: { entries: () => [] },
        text: async () => JSON.stringify({ error: 'Bucket not found' }),
      });

      const client = new S3Client({
        edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
        getAccessToken,
        getActiveSiteId,
      });

      await expect(client.listObjects('')).rejects.toThrow('Bucket not found');
    });

    it('prefixes the message with "Upgrade required: " when upgrade_required is true', async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        ok: false,
        status: 402,
        statusText: 'Payment Required',
        headers: { entries: () => [] },
        text: async () =>
          JSON.stringify({
            error: 'S3 media library requires a paid plan',
            upgrade_required: true,
          }),
      });

      const client = new S3Client({
        edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
        getAccessToken,
        getActiveSiteId,
      });

      await expect(client.listObjects('')).rejects.toThrow(
        'Upgrade required: S3 media library requires a paid plan',
      );
    });

    it('falls back to the raw-body format for a non-JSON error body', async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        ok: false,
        status: 502,
        statusText: 'Bad Gateway',
        headers: { entries: () => [] },
        text: async () => '<html>Bad Gateway</html>',
      });

      const client = new S3Client({
        edgeBaseUrl: 'https://edge.example.test/functions/v1/integrations/s3',
        getAccessToken,
        getActiveSiteId,
      });

      await expect(client.listObjects('')).rejects.toThrow(
        'S3 API error: 502 - <html>Bad Gateway</html>',
      );
    });
  });
});
