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)}` : ''}`;

export async function apiPost(request, action, op, form = {}) {
  const res = await request.post(postPath(action, op), { form });
  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) });
    }
  }
}
