import Cookies from "js-cookie";
import { MeDto } from "@/shared/dto/user/meDto";
import {
  getProfile,
  RegisterWithFaydaResponse,
} from "@/shared/services/authService";
import {
  getAuthCookieOptions,
  setAuthCookies,
} from "@/shared/utils/authPersistence";
import type { VerifiedCitizen } from "@/complaints/types/complaint.types";

function unwrapApiData<T>(payload: T | { data?: T }): T {
  if (
    payload &&
    typeof payload === "object" &&
    "data" in payload &&
    payload.data &&
    typeof payload.data === "object"
  ) {
    return payload.data;
  }

  return payload as T;
}

function resolveLocalizedName(
  name: string | { am?: string; en?: string } | undefined,
  preferredLanguage = "en",
): string {
  if (!name) return "";
  if (typeof name === "string") return name.trim();
  if (preferredLanguage === "am") {
    return (name.am || name.en || "").trim();
  }
  return (name.en || name.am || "").trim();
}

function resolveProfileDisplayName(
  profile: MeDto | null | undefined,
  preferredLanguage = "en",
): string {
  if (!profile) return "";

  const extendedProfile = profile as MeDto & {
    fullName?: string;
    firstName?: string;
    lastName?: string;
    faydaId?: string;
  };

  const localizedName = resolveLocalizedName(profile.name, preferredLanguage);
  if (localizedName) return localizedName;

  const combinedName = [extendedProfile.firstName, extendedProfile.lastName]
    .filter(Boolean)
    .join(" ")
    .trim();
  if (combinedName) return combinedName;

  if (extendedProfile.fullName?.trim()) {
    return extendedProfile.fullName.trim();
  }

  if (profile.username?.trim()) return profile.username.trim();
  if (profile.email?.trim()) return profile.email.trim();
  if (profile.phoneNumber?.trim()) return profile.phoneNumber.trim();

  return "";
}

export function mapRegisterWithFaydaCitizen(
  data: RegisterWithFaydaResponse,
  preferredLanguage = "en",
  profile?: MeDto | null,
): VerifiedCitizen {
  const fullName =
    String(
      data.citizen?.fullName ??
        data.fullName ??
        data.user?.fullName ??
        resolveLocalizedName(data.user?.name, preferredLanguage) ??
        resolveProfileDisplayName(profile, preferredLanguage) ??
        "",
    ).trim();

  const faydaId = String(
    data.citizen?.faydaId ??
      data.faydaId ??
      data.user?.faydaId ??
      (profile as { faydaId?: string } | undefined)?.faydaId ??
      profile?.username ??
      "",
  )
    .trim()
    .replace(/\s+/g, "");

  return { fullName, faydaId };
}

export async function persistFaydaRegistrationAuth(
  data: RegisterWithFaydaResponse,
): Promise<MeDto | null> {
  const token = data.token?.trim();
  const refreshToken = data.refreshToken?.trim();

  if (!token) {
    return null;
  }

  const cookieOptions = getAuthCookieOptions(false);
  setAuthCookies({
    token,
    refreshToken: refreshToken ?? "",
    rememberMe: false,
  });

  try {
    const { data: profile } = await getProfile({
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    const userDetails = unwrapApiData(profile as MeDto | { data?: MeDto });

    Cookies.set(
      "auth-user",
      JSON.stringify({
        ...userDetails,
        id: userDetails.id,
        name: userDetails.name,
        permissions: userDetails.permissions,
        roles: userDetails.roles,
      }),
      cookieOptions,
    );

    const firstPositionId =
      userDetails.employee?.[0]?.positions?.[0]?.employeePositionId;
    if (firstPositionId) {
      Cookies.set("current-position-id", firstPositionId, cookieOptions);
    }

    return userDetails;
  } catch {
    return null;
  }
}
