import type { Page } from "playwright";
import type { AxelSelectionBridge } from "@/workers/rpa/axel-selection-bridge";
import { fetchAxelPlaceLocation } from "@/workers/rpa/axel-place-prefetch";
import {
  CHECK_PICKUP_IN_REACT_STATE,
  INJECT_REACT_STATE,
} from "@/workers/rpa/fix-place/browser-eval-scripts";

export async function commitViaReactStateInjection(
  page: Page,
  bridge: AxelSelectionBridge,
  placeId: string,
  description: string,
  side: "pickup" | "delivery",
  pickupInfo?: {
    placeId: string;
    description: string;
    location: Record<string, unknown>;
  },
): Promise<{ ok: boolean }> {
  if (side === "delivery") {
    const pickupStillPresent = await page.evaluate(CHECK_PICKUP_IN_REACT_STATE);
    if (!pickupStillPresent && pickupInfo) {
      const reinjected = await page.evaluate(INJECT_REACT_STATE, {
        sideArg: "pickup",
        pid: pickupInfo.placeId,
        loc: pickupInfo.location,
        desc: pickupInfo.description,
      });
      if (!reinjected) {
        return { ok: false };
      }
      bridge.recordPlaceCommit(pickupInfo.placeId);
      bridge.setPlaceDetails(pickupInfo.placeId, pickupInfo.location);
      await page.waitForTimeout(400);
    }
  }

  const { ok, location } = await fetchAxelPlaceLocation(page, placeId);
  if (!ok || !location) {
    return { ok: false };
  }

  const injected = await page.evaluate(INJECT_REACT_STATE, {
    sideArg: side,
    pid: placeId,
    loc: location as Record<string, unknown>,
    desc: description,
  });

  if (!injected) {
    return { ok: false };
  }

  bridge.recordPlaceCommit(placeId);
  bridge.setPlaceDetails(placeId, location as Record<string, unknown>);

  await page.waitForTimeout(800);

  return { ok: true };
}
