import { expect } from '@playwright/test';

export const adminPath = (page) => `/wp-admin/admin.php?page=${page}`;
export const postPath = (action, op = '') => `/wp-admin/admin-post.php?action=${encodeURIComponent(action)}${op ? `&op=${encodeURIComponent(op)}` : ''}`;

const actionNoncePage = {
  feca_mailshots_data_sources_api: 'feca-mailshot-data-sources',
  feca_mailshots_mailshots_api: 'feca-mailshots-mailshots',
  feca_mailshots_test_api: 'feca-mailshots-test',
  feca_mailshots_run_api: 'feca-mailshots-run'
};

const nonceCache = new Map();

async function fetchNonceForAction(request, action) {
  const page = actionNoncePage[action];
  if (!page) {
    return '';
  }
  if (nonceCache.has(action)) {
    return nonceCache.get(action) || '';
  }

  const res = await request.get(adminPath(page));
  const html = await res.text();
  const match = html.match(/name="_wpnonce"\s+value="([^"]+)"/i);
  const nonce = match && match[1] ? String(match[1]) : '';
  if (nonce) {
    nonceCache.set(action, nonce);
  }
  return nonce;
}

export async function apiPost(request, action, op, form = {}) {
  const nextForm = { ...form };
  if (!nextForm._wpnonce) {
    const nonce = await fetchNonceForAction(request, action);
    if (nonce) {
      nextForm._wpnonce = nonce;
    }
  }
  const res = await request.post(postPath(action, op), { form: nextForm });
  const status = res.status();
  const raw = await res.text();
  let decoded;
  try {
    decoded = JSON.parse(raw);
  } catch {
    decoded = { ok: false, error: `Non-JSON response (HTTP ${status})`, raw };
  }
  return { _httpStatus: status, ...decoded };
}

export async function apiList(request, action) {
  return await apiPost(request, action, 'list', {});
}

export async function ensureDataSource(request, name, dslText) {
  const out = await apiPost(request, 'feca_mailshots_data_sources_api', 'save', {
    name,
    dsl_text: dslText
  });
  expect(out.ok).toBeTruthy();
  return out;
}

export async function ensureMailshot(request, payload) {
  const out = await apiPost(request, 'feca_mailshots_mailshots_api', 'save', payload);
  expect(out.ok).toBeTruthy();
  return out;
}

export async function cleanupByNames(request, { dataSourceNames = [], mailshotPurposes = [] } = {}) {
  const msList = await apiList(request, 'feca_mailshots_mailshots_api');
  for (const row of msList.items || []) {
    if (mailshotPurposes.includes(String(row.Purpose || ''))) {
      await apiPost(request, 'feca_mailshots_mailshots_api', 'delete', { id: String(row.id || 0) });
    }
  }

  const dsList = await apiList(request, 'feca_mailshots_data_sources_api');
  for (const row of dsList.items || []) {
    if (dataSourceNames.includes(String(row.name || ''))) {
      await apiPost(request, 'feca_mailshots_data_sources_api', 'delete', { id: String(row.ID || row.id || 0) });
    }
  }
}
