import { Page } from '@playwright/test';
import { mock_site_domain } from './env';

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_v3_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: [] }) });
  });
}

export default { minimal_event, minimal_badge, attach_minimal_v3_routes };
