import type { ApiSettings, AuthGroupsInfo, AuthInfo, AuthProfileInfo, AuthRolesInfo, AuthSessionInfo, AuthShellInfo, LoginResponse, UserUiPreferences } from "../types";
import { apiFetch } from "./client";

export async function login(
  settings: ApiSettings,
  payload: { email: string; password: string }
): Promise<LoginResponse> {
  return apiFetch<LoginResponse>({ ...settings, accessToken: "", apiKey: "" }, "/api/v1/auth/login", {
    method: "POST",
    body: JSON.stringify(payload)
  });
}

export async function fetchMe(settings: ApiSettings): Promise<AuthInfo> {
  return apiFetch<AuthInfo>(settings, "/api/v1/auth/me");
}

export async function fetchSession(settings: ApiSettings): Promise<AuthSessionInfo> {
  return apiFetch<AuthSessionInfo>(settings, "/api/v1/auth/session", { cache: "no-store" });
}

export async function fetchShellAuth(settings: ApiSettings): Promise<AuthShellInfo> {
  return apiFetch<AuthShellInfo>(settings, "/api/v1/auth/shell", { cache: "no-store" });
}

export async function fetchAuthProfile(settings: ApiSettings): Promise<AuthProfileInfo> {
  return apiFetch<AuthProfileInfo>(settings, "/api/v1/auth/profile", { cache: "no-store" });
}

export async function fetchAuthRoles(settings: ApiSettings): Promise<AuthRolesInfo> {
  return apiFetch<AuthRolesInfo>(settings, "/api/v1/auth/roles", { cache: "no-store" });
}

export async function fetchAuthGroups(settings: ApiSettings): Promise<AuthGroupsInfo> {
  return apiFetch<AuthGroupsInfo>(settings, "/api/v1/auth/groups", { cache: "no-store" });
}

export async function switchTenant(settings: ApiSettings, tenantId: string): Promise<AuthShellInfo> {
  return apiFetch<AuthShellInfo>(settings, "/api/v1/auth/switch-tenant", {
    method: "POST",
    body: JSON.stringify({ tenant_id: tenantId })
  });
}

export async function logout(settings: ApiSettings): Promise<void> {
  await apiFetch(settings, "/api/v1/auth/logout", { method: "POST" });
}

export async function updateProfile(
  settings: ApiSettings,
  payload: {
    display_name?: string | null;
    tenant_display_name?: string | null;
    preferred_language?: string | null;
    enabled_language_codes?: string[] | null;
    ui_preferences?: Partial<UserUiPreferences> | null;
  }
): Promise<AuthProfileInfo> {
  return apiFetch<AuthProfileInfo>(settings, "/api/v1/auth/profile", {
    method: "PATCH",
    body: JSON.stringify(payload)
  });
}
