5) Registration job → OpenSRS SW_REGISTER
// server/jobs/registerDomain.ts
import { loadOrder, saveOrder } from "../util/store";
import { openSrsRegistrar } from "../domains/providers/opensrs";

export async function registerDomain(orderId: string) {
  const order = await loadOrder(orderId);
  if (!order) throw new Error("Order not found");

  if (order.status !== "paid" && order.status !== "registering") {
    throw new Error(`Order not payable: ${order.status}`);
  }

  order.status = "registering";
  await saveOrder(order);

  try {
    const res = await openSrsRegistrarRegister({
      domain: order.domain,
      years: order.years,
      privacy: order.privacy,
      nameservers: undefined, // use default; or pass user-provided
      contact: order.contact,
    });

    if (!res.success) throw new Error(res.message || "registration failed");

    order.status = "active";
    order.providerRegId = res.registrationId;
    await saveOrder(order);
    return true;
  } catch (err: any) {
    order.status = "failed";
    order.errorMessage = err?.message || String(err);
    await saveOrder(order);
    return false;
  }
}

// Thin wrapper calling OpenSRS adapter’s registration
async function openSrsRegistrarRegister(input: {
  domain: string; years: number; privacy: boolean; nameservers?: string[];
  contact: { first: string; last: string; email: string; phone: string; address1: string; city: string; state: string; postal: string; country: string; org?: string; }
}) {
  // reuse your openSrsRegistrar from earlier; add a register() there
  const res = await fetch(process.env.OPENSRS_BASE!, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Username": process.env.OPENSRS_USER!,
      "X-Signature": process.env.OPENSRS_KEY!,
    },
    body: JSON.stringify({
      protocol: "XCP",
      action: "SW_REGISTER",
      object: "DOMAIN",
      attributes: {
        domain: input.domain,
        period: input.years,
        contact_set: {
          owner: input.contact,
          admin: input.contact,
          billing: input.contact,
          tech: input.contact,
        },
        private: input.privacy ? 1 : 0,
        // nameservers: "ns1.example.com,ns2.example.com"  // if you have defaults
      }
    }),
  });

  const text = await res.text();
  let json: any;
  try { json = JSON.parse(text); } catch { throw new Error(`OpenSRS non-JSON: ${text.slice(0,200)}`); }

  const ok = json?.is_success === 1;
  return {
    success: ok,
    registrationId: ok ? json.attributes?.registration_id : undefined,
    message: json?.response_text,
  };
}