import type { BrokerEntry } from "./broker.registry";

export interface PersonalInfo {
  fullName: string;
  email?: string;
  phone?: string;
  address?: string;
  city?: string;
  state?: string;
  zip?: string;
  dob?: string;
}

export interface FormPayload {
  url: string;
  fields: Record<string, string>;
  method: "GET" | "POST";
}

export async function submitAutomatedRemoval(
  broker: BrokerEntry,
  personalInfo: PersonalInfo,
): Promise<{ success: boolean; requestId?: string; error?: string }> {
  if (broker.removalMethod !== "AUTOMATED") {
    return { success: false, error: `Broker ${broker.name} does not support automated removal` };
  }

  try {
    // Placeholder: actual API integration per broker would go here
    // Each automated broker would have its own adapter that calls their API
    return { success: true, requestId: crypto.randomUUID() };
  } catch (err) {
    return { success: false, error: err instanceof Error ? err.message : "Unknown error" };
  }
}

export function generateFormPayload(broker: BrokerEntry, personalInfo: PersonalInfo): FormPayload {
  const fields: Record<string, string> = {
    full_name: personalInfo.fullName,
  };

  if (personalInfo.email) fields.email = personalInfo.email;
  if (personalInfo.phone) fields.phone = personalInfo.phone;
  if (personalInfo.address) fields.address = personalInfo.address;
  if (personalInfo.city) fields.city = personalInfo.city;
  if (personalInfo.state) fields.state = personalInfo.state;
  if (personalInfo.zip) fields.zip = personalInfo.zip;
  if (personalInfo.dob) fields.date_of_birth = personalInfo.dob;

  return {
    url: broker.removalUrl,
    fields,
    method: "POST",
  };
}

export async function sendRemovalEmail(
  broker: BrokerEntry,
  personalInfo: PersonalInfo,
): Promise<{ success: boolean; error?: string }> {
  // Placeholder: use notification service (task 14) to send the email
  // The email would include the specific instructions for this broker
  try {
    return { success: true };
  } catch (err) {
    return { success: false, error: err instanceof Error ? err.message : "Unknown error" };
  }
}

export async function trackRemovalStatus(
  broker: BrokerEntry,
  requestId: string,
): Promise<{ status: "pending" | "submitted" | "completed" | "failed"; detail?: string }> {
  // Placeholder: poll broker API or check email for status updates
  return { status: "pending" };
}
