import { getAuthToken } from "./auth-token";

export interface MyLanguage {
  id: number;
  name: string;
  code: string;
}

interface Result<T> {
  success: boolean;
  message: string;
  data: T;
}

async function request(path: string, init: RequestInit = {}) {
  const token = getAuthToken();

  if (!token) {
    return { ok: false, body: { message: "Please sign in to continue." } as any };
  }

  try {
    const response = await fetch(path, {
      ...init,
      headers: {
        Accept: "application/json",
        ...(init.body ? { "Content-Type": "application/json" } : {}),
        Authorization: token.startsWith("Bearer ") ? token : `Bearer ${token}`,
      },
      cache: "no-store",
    });

    const text = await response.text();

    let body: any = {};

    try {
      body = text ? JSON.parse(text) : {};
    } catch {
      body = { message: text };
    }

    return {
      ok: response.ok && body?.success !== false && body?.status !== false,
      body,
    };
  } catch {
    return { ok: false, body: { message: "Unable to reach the server. Please try again." } as any };
  }
}

// GET/PUT /user/my-languages share one response shape:
// { data: { myLanguages: "3,1", languageIds: [3,1], languages: [{id, languageName, languageCode}] } }
function parseLanguages(body: any): MyLanguage[] {
  const list = body?.data?.languages;

  if (!Array.isArray(list)) return [];

  return list
    .map((item: any) => ({
      id: Number(item.id),
      name: String(item.languageName ?? item.name ?? "").trim(),
      code: String(item.languageCode ?? item.code ?? ""),
    }))
    .filter((item) => item.id && item.name);
}

export async function getMyLanguages(): Promise<Result<MyLanguage[]>> {
  const { ok, body } = await request("/api/user/my-languages");

  return { success: ok, message: body?.message ?? "", data: ok ? parseLanguages(body) : [] };
}

// Replaces the whole selection — always send every selected id, in order.
export async function updateMyLanguages(languageIds: number[]): Promise<Result<MyLanguage[]>> {
  const { ok, body } = await request("/api/user/my-languages", {
    method: "PUT",
    body: JSON.stringify({ languageIds }),
  });

  return { success: ok, message: body?.message ?? "", data: ok ? parseLanguages(body) : [] };
}

// Every language the user can pick. There is no user-side master list endpoint
// in the API, so this reads the shared master table through the astrologer
// master endpoint (same languages table, same ids) with the customer's token.
export async function getLanguageOptions(): Promise<Result<MyLanguage[]>> {
  const { ok, body } = await request("/api/astrologer/master/languages");

  const list = body?.data?.languages ?? body?.data ?? body?.languages ?? [];

  const options: MyLanguage[] = Array.isArray(list)
    ? list
        .map((item: any) => ({
          id: Number(item.id ?? item.language_id),
          name: String(item.language_name ?? item.languageName ?? item.name ?? "").trim(),
          code: String(item.language_code ?? item.languageCode ?? item.code ?? ""),
        }))
        .filter((item) => item.id && item.name)
    : [];

  return {
    success: ok && options.length > 0,
    message: body?.message ?? "",
    data: options,
  };
}
