export type ZerodhaCallbackParams = {
  flow: string;
  status: string;
  requestToken: string;
  state: string;
  error: string;
  errorDescription: string;
};

export function parseZerodhaCallbackParams(search: string): ZerodhaCallbackParams {
  const params = new URLSearchParams(search);
  return {
    flow: (params.get("flow") || "").trim(),
    status: (params.get("status") || "").trim(),
    requestToken: (params.get("request_token") || "").trim(),
    state: (params.get("state") || "").trim(),
    error: (params.get("error") || params.get("error_type") || "").trim(),
    errorDescription: (params.get("error_description") || "").trim(),
  };
}

export function buildZerodhaBackendCallbackUrl(params: ZerodhaCallbackParams): string {
  const callbackPath = params.flow === "reconnect" ? "/broker/callback" : "/broker/zerodha/callback";
  const search = new URLSearchParams();
  if (params.requestToken) {
    search.set("request_token", params.requestToken);
  }
  if (params.state) {
    search.set("state", params.state);
  }
  return `${callbackPath}?${search.toString()}`;
}
