import { expect, test } from "@playwright/test";
import { API_URL, registerVerifyLogin, uniqueEmail } from "../helpers/api";

const tinyPng = Buffer.from(
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
  "base64"
);

test.describe("§15.7 scenario 10: Avatar validation", () => {
  test("rejects svg, oversize and accepts valid png", async ({ request }) => {
    const session = await registerVerifyLogin(request, uniqueEmail("e2e-avatar"));
    const headers = { Authorization: `Bearer ${session.accessToken}` };

    const svg = await request.post(`${API_URL}/api/v1/users/me/avatar`, {
      headers,
      multipart: {
        file: {
          name: "avatar.svg",
          mimeType: "image/svg+xml",
          buffer: Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'></svg>")
        }
      }
    });
    expect(svg.status()).toBe(400);

    const oversize = await request.post(`${API_URL}/api/v1/users/me/avatar`, {
      headers,
      multipart: {
        file: {
          name: "big.png",
          mimeType: "image/png",
          buffer: Buffer.concat([tinyPng, Buffer.alloc(2 * 1024 * 1024 + 1)])
        }
      }
    });
    expect(oversize.status()).toBe(400);
    expect((await oversize.json()).detail).toBe("FILE_TOO_LARGE");

    const valid = await request.post(`${API_URL}/api/v1/users/me/avatar`, {
      headers,
      multipart: {
        file: {
          name: "avatar.png",
          mimeType: "image/png",
          buffer: tinyPng
        }
      }
    });
    expect(valid.ok()).toBeTruthy();
    expect((await valid.json()).profile.avatar_url).toContain("/api/v1/media/files/avatars/");
  });
});
