import { test, expect, registerUser, createListing } from '../fixtures';

test.describe('POST /listings/:id/media — Media upload', () => {
  let accessToken: string;
  let listingId: string;

  test.beforeAll(async ({ request }) => {
    const { accessToken: token } = await registerUser(request);
    accessToken = token;

    // Create a listing to attach media to
    const { listing } = await createListing(request, token);
    listingId = listing.id;
  });

  test('rejects unauthenticated media upload', async ({ request }) => {
    const res = await request.post(`listings/${listingId}/media`, {
      multipart: {
        file: {
          name: 'test.jpg',
          mimeType: 'image/jpeg',
          buffer: Buffer.from('fake-jpeg-data'),
        },
      },
    });

    expect(res.status()).toBe(401);
  });

  test('rejects upload without file', async ({ request }) => {
    const res = await request.post(`listings/${listingId}/media`, {
      headers: { Authorization: `Bearer ${accessToken}` },
      multipart: {
        caption: 'Missing file',
      },
    });

    expect(res.ok()).toBeFalsy();
    expect([400, 422]).toContain(res.status());
  });

  test('rejects upload with invalid MIME type', async ({ request }) => {
    const res = await request.post(`listings/${listingId}/media`, {
      headers: { Authorization: `Bearer ${accessToken}` },
      multipart: {
        file: {
          name: 'test.pdf',
          mimeType: 'application/pdf',
          buffer: Buffer.from('fake-pdf-data'),
        },
      },
    });

    expect(res.ok()).toBeFalsy();
    expect([400, 415, 422]).toContain(res.status());
  });

  test('rejects upload for non-existent listing', async ({ request }) => {
    const res = await request.post('listings/non-existent-id/media', {
      headers: { Authorization: `Bearer ${accessToken}` },
      multipart: {
        file: {
          name: 'test.jpg',
          mimeType: 'image/jpeg',
          buffer: Buffer.from('fake-jpeg-data'),
        },
      },
    });

    expect(res.ok()).toBeFalsy();
    expect([400, 404]).toContain(res.status());
  });
});
