import { expect, test } from "@playwright/test";

test.describe("Users Bulk Upload UUID Import Policy", () => {
  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      window.localStorage.setItem("locale", "ko");
      window.localStorage.setItem("admin_session", "fake-token");
      (
        window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
      )._IS_TEST_MODE = true;

      const authority = "http://localhost:5000/oidc";
      const client_id = "adminfront";
      const key = `oidc.user:${authority}:${client_id}`;
      const authData = {
        access_token: "fake-token",
        token_type: "Bearer",
        profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
        expires_at: Math.floor(Date.now() / 1000) + 36000,
      };
      window.localStorage.setItem(key, JSON.stringify(authData));
    });

    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin-user",
            name: "Admin",
            role: "super_admin",
            manageableTenants: [],
          },
          headers,
        });
      }
      if (url.includes("/admin/users") && !url.includes("/bulk")) {
        return route.fulfill({
          json: { items: [], total: 0, limit: 50, offset: 0 },
          headers,
        });
      }
      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: { items: [], total: 0, limit: 100, offset: 0 },
          headers,
        });
      }
      return route.fulfill({ json: { items: [], total: 0 }, headers });
    });

    await page.route("**/oidc/**", async (route) => {
      await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
    });
  });

  test("should not include exported user_id or uuid in bulk upload payload", async ({
    page,
  }) => {
    let bulkPayload = "";
    const testUuid = "550e8400-e29b-41d4-a716-446655440000";

    await page.route("**/api/v1/admin/users/bulk", async (route) => {
      bulkPayload = route.request().postData() ?? "";
      return route.fulfill({
        json: {
          results: [
            { email: "uuid@test.com", success: true, userId: "kratos-id" },
          ],
        },
        headers: { "Access-Control-Allow-Origin": "*" },
      });
    });

    await page.goto("/users");
    await page.getByTestId("user-data-mgmt-btn").click();
    await page
      .getByRole("menuitem", { name: /일괄 임포트|Bulk Import/i })
      .click();

    await page.locator('input[type="file"]').setInputFiles({
      name: "users_uuid.csv",
      mimeType: "text/csv",
      buffer: Buffer.from(
        `user_id,email,name,uuid\n${testUuid},uuid@test.com,UUID User,${testUuid}\n`,
      ),
    });

    await page.getByTestId("bulk-start-btn").click();
    await expect(page.getByText("uuid@test.com")).toBeVisible();

    const payload = JSON.parse(bulkPayload);
    expect(payload.users[0]).not.toHaveProperty("userId");
    expect(payload.users[0]).not.toHaveProperty("uuid");
    expect(payload.users[0]).not.toHaveProperty("id");
  });

  test("should treat id column as login id, not UUID import", async ({
    page,
  }) => {
    let bulkPayload = "";
    const testUuid = "550e8400-e29b-41d4-a716-446655440001";

    await page.route("**/api/v1/admin/users/bulk", async (route) => {
      bulkPayload = route.request().postData() ?? "";
      return route.fulfill({
        json: {
          results: [
            { email: "id-uuid@test.com", success: true, userId: "kratos-id" },
          ],
        },
        headers: { "Access-Control-Allow-Origin": "*" },
      });
    });

    await page.goto("/users");
    await page.getByTestId("user-data-mgmt-btn").click();
    await page
      .getByRole("menuitem", { name: /일괄 임포트|Bulk Import/i })
      .click();

    await page.locator('input[type="file"]').setInputFiles({
      name: "users_id.csv",
      mimeType: "text/csv",
      buffer: Buffer.from(
        `email,name,id\nid-uuid@test.com,ID UUID User,${testUuid}\n`,
      ),
    });

    await page.getByTestId("bulk-start-btn").click();

    const payload = JSON.parse(bulkPayload);
    expect(payload.users[0]).not.toHaveProperty("uuid");
    expect(payload.users[0].loginId).toBe(testUuid);
    expect(payload.users[0].metadata.naverworks_id).toBe(testUuid);
  });
});
