import type { Page } from '@playwright/test';
import { mock_site_domain, testing_account_id } from './env';
import { ae_app_local_data_defaults } from './ae_defaults';

export const minimal_event = (event_id: string) => ({
  data: {
    id: event_id,
    event_id: event_id,
    name: 'Test Event (minimal)',
    cfg_json: {},
    mod_pres_mgmt_json: {},
    mod_badges_json: {},
    mod_abstracts_json: {},
    mod_exhibits_json: {},
    mod_meetings_json: {},
  },
});

export const minimal_badge = (overrides: Record<string, any> = {}) => ({
  event_badge_id: 'badge-1',
  full_name_override: 'Test User',
  email: 'test@example.com',
  badge_type: 'test',
  ...overrides,
});

/**
 * Attach minimal V3 route handlers to a Playwright `page`.
 * - Responds to event GET, badge search/create/update/delete, and a simple site_domain/search.
 * - Keeps created badge state in-memory for the page session.
 */
export async function attach_minimal_routes(page: Page, event_id: string) {
  let created_badge: any = null;

  await page.route('**/v3/**', async (route) => {
    const req = route.request();
    const url = req.url();
    const method = req.method();

    if (url.includes('site_domain/search')) {
      return route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ data: [mock_site_domain] })
      });
    }

    if (url.includes(`/v3/crud/event/${event_id}`) && method === 'GET') {
      return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(minimal_event(event_id)) });
    }

    if (url.includes(`/v3/crud/event/${event_id}/event_badge/search`) && method === 'POST') {
      return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: created_badge ? [created_badge] : [] }) });
    }

    if (url.includes(`/v3/crud/event/${event_id}/event_badge`) && method === 'POST') {
      const post = await req.postData();
      const body = post ? JSON.parse(post) : {};
      created_badge = { ...minimal_badge(body) };
      return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ data: created_badge }) });
    }

    if (url.match(new RegExp(`/v3/crud/event/${event_id}/event_badge/.+`)) && (method === 'PATCH' || method === 'PUT')) {
      const post = await req.postData();
      const body = post ? JSON.parse(post) : {};
      if (created_badge) created_badge = { ...created_badge, ...body };
      return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: created_badge }) });
    }

    if (url.match(new RegExp(`/v3/crud/event/${event_id}/event_badge/.+`)) && method === 'DELETE') {
      created_badge = null;
      return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: true }) });
    }

    return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [] }) });
  });
}

/**
 * Seed localStorage with a trusted/manager session for the given event.
 *
 * Must be called via page.addInitScript — runs before page JS executes so the
 * store_versions.ts guard sees __version and leaves ae_loc intact.
 *
 * @param account_id  Defaults to testing_account_id from env.ts.
 */
export async function seed_trusted_session(
  page: Page,
  event_id: string,
  account_id: string = testing_account_id
): Promise<void> {
  await page.addInitScript(
    ([defaults, e_id, a_id]: [typeof ae_app_local_data_defaults, string, string]) => {
      const data: any = {
        ...defaults,
        account_id:           a_id,
        allow_access:         true,
        authenticated_access: true,
        trusted_access:       true,
        manager_access:       true,
        edit_mode:            false,
      };
      data.mod = { ...defaults.mod, events: { ...defaults.mod.events, event_id: e_id } };
      window.localStorage.setItem('ae_loc', JSON.stringify(data));
    },
    [ae_app_local_data_defaults, event_id, account_id] as [typeof ae_app_local_data_defaults, string, string]
  );
}

/**
 * One-call beforeEach setup for badge print/render tests.
 *
 * Wires:
 *   - page.on('pageerror') → stderr
 *   - attach_minimal_routes() — mock all /v3/ API calls
 *   - seed_trusted_session()     — seed ae_loc localStorage with trusted auth
 */
export async function setup_badge_test_page(page: Page, event_id: string): Promise<void> {
  page.on('pageerror', (err) => console.error(`BROWSER ERROR: ${err.message}`));
  await attach_minimal_routes(page, event_id);
  await seed_trusted_session(page, event_id);
}

export default { minimal_event, minimal_badge, attach_minimal_routes, seed_trusted_session, setup_badge_test_page };
