import { api } from "@/src/lib/api/client";

export type TenantCountry = {
  id: number;
  country_code: string;
  country_name: string;
  is_active: boolean;
  manager: {
    id: number;
    username: string;
    full_name: string;
    email: string;
  } | null;
  created_at: string;
};

export type CreateCountryPayload = {
  country_code: string;
  country_name: string;
  is_active?: boolean;
};

export type UpdateCountryPayload = {
  country_name?: string;
  is_active?: boolean;
};

// ─── Pays du tenant ──────────────────────────────────���────────────────────────

export async function listTenantCountries(): Promise<TenantCountry[]> {
  return api.request<TenantCountry[]>("/tenant/countries/", { method: "GET" });
}

export async function createTenantCountry(payload: CreateCountryPayload): Promise<TenantCountry> {
  return api.request<TenantCountry>("/tenant/countries/", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function updateTenantCountry(id: number, payload: UpdateCountryPayload): Promise<TenantCountry> {
  return api.request<TenantCountry>(`/tenant/countries/${id}/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function deleteTenantCountry(id: number): Promise<void> {
  await api.request(`/tenant/countries/${id}/`, { method: "DELETE" });
}

export async function setCountryManager(countryId: number, userId: number | null): Promise<TenantCountry> {
  return api.request<TenantCountry>(`/tenant/countries/${countryId}/set-manager/`, {
    method: "POST",
    body: JSON.stringify({ user_id: userId }),
  });
}

// ─── Pays assignés à un utilisateur ──────────────────────────────────────────

export async function listUserCountries(userId: number): Promise<TenantCountry[]> {
  return api.request<TenantCountry[]>(`/tenant/users/${userId}/countries/`, { method: "GET" });
}

export async function saveUserCountries(userId: number, countryIds: number[]): Promise<TenantCountry[]> {
  return api.request<TenantCountry[]>(`/tenant/users/${userId}/countries/save/`, {
    method: "POST",
    body: JSON.stringify({ country_ids: countryIds }),
  });
}

export async function assignAllCountriesToUser(userId: number): Promise<TenantCountry[]> {
  return api.request<TenantCountry[]>(`/tenant/users/${userId}/countries/assign-all/`, {
    method: "POST",
  });
}
