import { test, expect } from '@playwright/test';
import { ae_app_local_data_defaults } from './_helpers/ae_defaults';
import { testing_event_id, testing_account_id } from './_helpers/env';

const event_id = testing_event_id;

test.describe('Event Badge - interaction', () => {
  test.beforeEach(async ({ page }) => {
    page.on('pageerror', (err) => console.error(`BROWSER ERROR: ${err.message}`));
    page.on('console', (msg) => {
      if (msg.type() === 'error' || msg.type() === 'warning')
        console.error(`BROWSER [${msg.type().toUpperCase()}]: ${msg.text()}`);
    });

    // Minimal network mock: fulfill only what's necessary for the UI to render
    await page.route('**/v3/**', async (route) => {
      const req = route.request();
      const url = req.url();

      // Provide the minimal event payload for the settings page to render
      if (url.includes(`/v3/crud/event/${event_id}`) && req.method() === 'GET') {
        return route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ data: {
            id: event_id,
            event_id: event_id,
            name: 'Test Event for Badge Interaction',
            cfg_json: {},
            mod_pres_mgmt_json: {},
            mod_badges_json: {},
            mod_abstracts_json: {},
            mod_exhibits_json: {},
            mod_meetings_json: {}
          } })
        });
      }

      // For badge create requests, return a simple created envelope with a fixed id.
      if (url.includes(`/v3/crud/event/${event_id}/event_badge`) && req.method() === 'POST') {
        return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ data: { event_badge_id: 'new-badge-1' } }) });
      }

      // Default: empty envelope so other calls don't error
      return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [] }) });
    });

    page.on('dialog', async (dialog) => {
      await dialog.accept();
    });

    await page.addInitScript(
      ({ defaults, event_id, account_id }) => {
        const testData = {
          ...defaults,
          account_id: account_id,
          manager_access: true,
          administrator_access: true,
          edit_mode: true,
          mod: { ...defaults.mod, events: { ...defaults.mod.events, event_id: event_id } }
        };
        window.localStorage.setItem('ae_loc', JSON.stringify(testData));
      },
      { defaults: ae_app_local_data_defaults, event_id: event_id, account_id: testing_account_id }
    );
  });

  test('creates a badge via UI and posts to nested endpoint', async ({ page }) => {
    await page.goto(`/events/${event_id}/settings`);

    const add_btn = page.getByRole('button', { name: 'Add New Badge' });
    await expect(add_btn).toBeVisible();
    await add_btn.click();

    const form = page.locator('form:has-text("Create Badge")');
    await expect(form).toBeVisible();

    const full_name_input = form.locator('label:has-text("Full Name Override") input');
    await expect(full_name_input).toBeVisible();
    await full_name_input.fill('Test User');

    const email_input = form.locator('label:has-text("Email") input');
    await email_input.fill('testuser@example.com');

    const badge_type_select = form.locator('label:has-text("Badge Type") select');
    await badge_type_select.selectOption('test');

    const allow_tracking_checkbox = form.locator('label:has-text("Allow Tracking") input[type="checkbox"]');
    await allow_tracking_checkbox.check();

      const [create_request] = await Promise.all([
        page.waitForRequest((r) => r.url().includes(`/v3/crud/event/${event_id}/event_badge`) && r.method() === 'POST'),
        page.getByRole('button', { name: 'Create Badge' }).click()
      ]);

      const post_body = create_request.postData();
      const post_json = post_body ? JSON.parse(post_body) : {};
      expect(post_json.email).toBe('testuser@example.com');
      expect(post_json.full_name_override).toBe('Test User');

      // Use the request's response for reliability (page.request bypasses page.route otherwise)
      const response = await create_request.response();
      expect(response).not.toBeNull();
      const resp_json = response ? await response.json() : {};
      expect(resp_json).toBeDefined();
      expect(resp_json.data).toBeDefined();
      expect(resp_json.data.event_badge_id).toBe('new-badge-1');
  });
});
