import { apiRequest } from '@/shared/api/httpClient';
import type { ApiListResponse } from '@/shared/types/api';

export interface PermissionRef {
  readonly id: string;
  readonly name: string | null;
}

export interface AdminUserRow {
  readonly id: string;
  readonly name_prefix?: string | null;
  readonly firstName: string | null;
  readonly lastName: string | null;
  readonly phoneNumber?: string | null;
  readonly email: string;
  readonly avatar?: readonly { readonly privateUrl?: string | null }[];
  readonly app_role?: { id: string; name: string | null } | null;
  readonly organizations?: { id: string; name?: string | null; logo?: string | null } | null;
  readonly school?: { id: string; name?: string | null; logo?: string | null } | null;
  readonly campus?: { id: string; name?: string | null; logo?: string | null } | null;
  readonly class?: { id: string; name?: string | null; logo?: string | null } | null;
  readonly campusId?: string | null;
  readonly schoolId?: string | null;
  readonly classId?: string | null;
  readonly custom_permissions?: readonly PermissionRef[];
  readonly custom_permissions_filter?: readonly PermissionRef[];
}

export interface SaveUserData {
  readonly name_prefix?: string | null;
  readonly firstName?: string;
  readonly lastName?: string;
  readonly phoneNumber?: string | null;
  readonly email?: string;
  /** Avatar file private URL from the upload, or null to clear. */
  readonly avatar?: string | null;
  /** Role id. */
  readonly app_role?: string | null;
  /** Organization id. */
  readonly organizations?: string | null;
  readonly campusId?: string | null;
  readonly schoolId?: string | null;
  readonly classId?: string | null;
  /** Permission ids granted on top of the role. */
  readonly custom_permissions?: string[];
  /** Permission ids removed from the role. */
  readonly custom_permissions_filter?: string[];
}

export interface ListUsersParams {
  readonly query?: string;
  readonly app_role?: string;
  readonly classId?: string;
  readonly campusId?: string;
  readonly limit?: number;
  readonly page?: number;
  readonly field?: 'name' | 'email' | 'phoneNumber' | 'organization' | 'school' | 'campus' | 'role';
  readonly sort?: 'asc' | 'desc';
}

export interface ListUsersOptions {
  readonly signal?: AbortSignal;
}

export function listUsers(
  params?: ListUsersParams,
  options?: ListUsersOptions,
): Promise<ApiListResponse<AdminUserRow>> {
  const search = new URLSearchParams();
  if (params?.query) search.set('query', params.query);
  if (params?.app_role) search.set('app_role', params.app_role);
  if (params?.classId) search.set('classId', params.classId);
  if (params?.campusId) search.set('campusId', params.campusId);
  if (params?.limit !== undefined) search.set('limit', String(params.limit));
  if (params?.page !== undefined) search.set('page', String(params.page));
  if (params?.field) search.set('field', params.field);
  if (params?.sort) search.set('sort', params.sort);
  const qs = search.toString();
  const path = `/users${qs ? `?${qs}` : ''}`;
  return options?.signal
    ? apiRequest<ApiListResponse<AdminUserRow>>(path, { signal: options.signal })
    : apiRequest<ApiListResponse<AdminUserRow>>(path);
}

/** Creates a user; returns the new user id (for follow-up links e.g. guardians). */
export interface CreateUserResult {
  readonly id: string | null;
  readonly organizationId?: string | null;
}

export async function createUser(data: SaveUserData): Promise<CreateUserResult> {
  const result = await apiRequest<CreateUserResult | boolean>('/users', {
    method: 'POST',
    body: { data },
  });
  return typeof result === 'object' && result !== null ? result : { id: null };
}

export async function createOwnerWithOrganization(
  data: Omit<SaveUserData, 'app_role' | 'organizations'>,
): Promise<CreateUserResult> {
  return apiRequest<CreateUserResult>('/users/owner-with-organization', {
    method: 'POST',
    body: { data },
  });
}

export function updateUser(id: string, data: SaveUserData): Promise<unknown> {
  return apiRequest(`/users/${id}`, {
    method: 'PUT',
    body: { id, data },
  });
}

export function deleteUser(id: string): Promise<unknown> {
  return apiRequest(`/users/${id}`, { method: 'DELETE' });
}

export function linkGuardianStudent(
  guardianId: string,
  studentId: string,
): Promise<unknown> {
  return apiRequest('/guardian_students', {
    method: 'POST',
    body: { data: { guardianId, studentId } },
  });
}
