/** ShopSafe REST example for server-side Node.js 20+ (no package dependencies).
 * Keep SHOPSAFE_API_KEY in a server-side secret store; never ship it in browser code.
 * Persist the request ID and identical URL/cost/age fields before the first call.
 * Reuse them after a timeout or restart. Default maximum: zero AUD cents.
 * No automatic funding, cap changes, retries or transaction actions.
 *
 * import {createShopSafe} from './shopsafe_verify.mjs';
 * const api = createShopSafe(process.env.SHOPSAFE_API_KEY);
 * const account = await api.account();
 * const result = await api.verify({url:'https://example.com', requestId:'order-123-check-1'});
 * // Inspect result.status, freshness, verdict.coverage, evidence and risk_level.
 * // Use maxCostCents: 2 only after the owner authorises paid checks.
 */
const BASE_URL = 'https://shopsafe.com.au';

export class ShopSafeError extends Error {
  constructor(detail) {
    super(detail.error || 'request_unavailable');
    this.name = 'ShopSafeError';
    this.detail = detail;
  }
}

function uncertain(error = 'transport_interrupted') {
  return new ShopSafeError({error, retryable:true, next_action:'wait_and_retry',
    retry_after_seconds:1, charge_status:'check_original_request',
    retry_instruction:'Retry with the original request ID and identical parameters. Do not assume that no charge occurred.'});
}

export function createShopSafe(apiKey, {fetchImpl = globalThis.fetch} = {}) {
  if (typeof apiKey !== 'string' || !/^[\x21-\x7e]+$/.test(apiKey)) {
    throw new Error('Supply the API key through your server-side secret store.');
  }
  async function request(method, path, payload, timeoutMs = 45000) {
    let response;
    try {
      response = await fetchImpl(BASE_URL + path, {
        method, headers:{Authorization:`Bearer ${apiKey}`, Accept:'application/json', 'Content-Type':'application/json'},
        body:payload === undefined ? undefined : JSON.stringify(payload),
        redirect:'error', signal:AbortSignal.timeout(timeoutMs)
      });
    } catch {
      throw uncertain(); // Never include transport errors or request headers.
    }
    if (response.status >= 300 && response.status < 400) {
      throw new ShopSafeError({error:'unexpected_redirect', retryable:false,
        next_action:'contact_support', charge_status:'check_original_request'});
    }
    let data;
    try { data = await response.json(); } catch { throw uncertain('invalid_service_response'); }
    if (!data || typeof data !== 'object' || Array.isArray(data)) throw uncertain('invalid_service_response');
    if (response.status !== 200) {
      if (typeof data.error !== 'string' || typeof data.next_action !== 'string') throw uncertain('invalid_service_response');
      throw new ShopSafeError(data);
    }
    return data;
  }
  return {
    account:() => request('GET','/api/v1/account'),
    batch:(id) => {
      if (typeof id !== 'string' || !/^[a-f0-9]{32}$/.test(id)) throw new Error('Use the batch ID returned by the service.');
      return request('GET','/api/v1/verification-batches/' + id);
    },
    verifyBatch:({urls, requestId, maxTotalCostCents = 0, maxAgeSeconds = 300}) => {
      if (!Array.isArray(urls) || urls.length < 1 || urls.length > 10 || !urls.every(u => typeof u === 'string' && u.length && u.length <= 2048)) throw new Error('Supply one to ten public URLs, without credentials or login/reset secrets.');
      if (typeof requestId !== 'string' || !/^[a-zA-Z0-9._-]{1,64}$/.test(requestId)) throw new Error('Persist the request ID and ordered URL list before the first call.');
      if (!Number.isInteger(maxTotalCostCents) || maxTotalCostCents < 0 || maxTotalCostCents > 100) throw new Error('Total authorised batch ceiling must be 0 to 100 integer AUD cents.');
      if (!Number.isInteger(maxAgeSeconds) || maxAgeSeconds < 0 || maxAgeSeconds > 300) throw new Error('Maximum evidence age must be 0 to 300 seconds.');
      return request('POST','/api/v1/verification-batches',{urls, idempotency_key:requestId,
        max_total_cost_aud_cents:maxTotalCostCents, max_age_seconds:maxAgeSeconds},90000);
    },
    verification:(id) => {
      if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(id)) throw new Error('Use the verification ID returned by the service.');
      return request('GET','/api/v1/verifications/' + id);
    },
    verify:({url, requestId, maxCostCents = 0, maxAgeSeconds = 300}) => {
      if (typeof requestId !== 'string' || !/^[a-zA-Z0-9._-]{1,64}$/.test(requestId)) throw new Error('Supply the persistent request ID (1 to 64 letters, digits, dots, underscores or hyphens).');
      if (!Number.isInteger(maxCostCents) || maxCostCents < 0 || maxCostCents > 100) throw new Error('Authorised maximum must be 0 to 100 integer AUD cents.');
      if (!Number.isInteger(maxAgeSeconds) || maxAgeSeconds < 0 || maxAgeSeconds > 300) throw new Error('Maximum evidence age must be 0 to 300 seconds.');
      if (typeof url !== 'string' || !url.length || url.length > 2048) throw new Error('Supply the public URL, without credentials or login/reset secrets.');
      return request('POST','/api/v1/verifications',{url, idempotency_key:requestId,
        max_cost_aud_cents:maxCostCents, max_age_seconds:maxAgeSeconds});
    }
  };
}

/** Freshness/coverage only. True does not authorise a transaction. */
export function currentCompleteEvidence(result, now = Date.now()) {
  const verdict = result?.verdict;
  // Reject timezone-less timestamps rather than interpreting them as local.
  const expiry = verdict?.expires_at;
  return result?.status === 'complete' && result?.freshness === 'fresh' && verdict?.coverage === 'complete' &&
    typeof expiry === 'string' && /(?:Z|[+-]\d\d:\d\d)$/.test(expiry) && Date.parse(expiry) > now;
}
