export type JobSeekerProfile = {
  id: string;
  user_id: string;
  full_name?: string | null;
  location?: string | null;
  summary?: string | null;
  experience_years?: number | null;
  skills?: string[] | null;
  resume_url?: string | null;
  status?: string | null;
  bio?: string | null;
  custom_data?: Record<string, unknown> | null;
};

// The K8s ingress routes any /api/* path directly to the Rust gateway service —
// there is no /api/gateway indirection in production (see ~/lib/api.ts). Hit
// the path as-is, and send the same Authorization bearer token every other
// authenticated call uses — AuthUser on the backend only reads that header,
// there is no cookie-based fallback.
function getAuthHeaders(): Record<string, string> {
  const token = typeof window !== 'undefined'
    ? (sessionStorage.getItem('nxtgauge_access_token') || '')
    : '';
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

async function apiFetch(path: string, opts?: RequestInit) {
  return fetch(path, {
    ...opts,
    credentials: 'include',
    headers: { ...getAuthHeaders(), ...(opts?.headers ?? {}) },
  });
}

function asObject(value: unknown): Record<string, unknown> {
  return value && typeof value === 'object' && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {};
}

export async function readJobSeekerProfile(): Promise<JobSeekerProfile | null> {
  try {
    const res = await apiFetch('/api/jobseeker/profile/me');
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

export async function updateJobSeekerCustomData(
  mutator: (currentCustomData: Record<string, unknown>) => Record<string, unknown>,
): Promise<JobSeekerProfile> {
  const existing = await readJobSeekerProfile();
  const currentCustomData = asObject(existing?.custom_data);
  const nextCustomData = mutator(currentCustomData);

  const payload = {
    full_name: existing?.full_name ?? null,
    location: existing?.location ?? null,
    summary: existing?.summary ?? null,
    experience_years: typeof existing?.experience_years === 'number' ? existing.experience_years : 0,
    skills: Array.isArray(existing?.skills) ? existing.skills : [],
    resume_url: existing?.resume_url ?? null,
    bio: existing?.bio ?? null,
    custom_data: nextCustomData,
  };

  const res = await apiFetch('/api/jobseeker/profile/me', {
    method: 'PATCH',
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    throw new Error(String(data?.error || data?.message || 'Failed to update job seeker data.'));
  }
  return await res.json();
}
