import { api, API_BASE_URL } from "@/lib/api-client";
import { asPaginated, asRecordData } from "@/lib/odoo-api";
import type { User, PaginatedResponse, PaginationParams, ApiSuccessResponse } from "@/types";

export interface UserListParams extends PaginationParams {
  type?: string;
  entity_id?: number;
}

function mapPortalUser(raw: Record<string, unknown>): User {
  return {
    id: raw.id as number,
    name: String(raw.name || ""),
    email: String(raw.email ?? raw.login ?? ""),
    login: String(raw.login ?? raw.email ?? ""),
    user_type: (raw.user_type as User["user_type"]) || "student",
    is_verified: Boolean(raw.is_verified ?? true),
    entities: Array.isArray(raw.entities) ? (raw.entities as User["entities"]) : [],
    classrooms: Array.isArray(raw.classrooms) ? (raw.classrooms as string[]) : [],
    phone: raw.phone as string | undefined,
    gender: raw.gender as string | undefined,
    student_id: raw.student_id as string | undefined,
  };
}

export const usersService = {
  async list(params: UserListParams): Promise<PaginatedResponse<User>> {
    const raw = await api.get<unknown>("/users/list", params as Record<string, string | number | boolean | undefined>);
    const p = asPaginated<Record<string, unknown>>(raw);
    return { ...p, items: p.items.map(mapPortalUser) };
  },

  async getById(id: number): Promise<User> {
    const raw = await api.get<unknown>(`/users/${id}`);
    return mapPortalUser(asRecordData<Record<string, unknown>>(raw));
  },

  async update(id: number, data: Partial<User>): Promise<User> {
    const raw = await api.patch<unknown>(`/users/update`, { id, ...data });
    return mapPortalUser(asRecordData<Record<string, unknown>>(raw));
  },

  async create(data: Partial<User>): Promise<User> {
    const raw = await api.post<unknown>("/users/create", data);
    return mapPortalUser(asRecordData<Record<string, unknown>>(raw));
  },

  async createBatch(data: { users: Partial<User>[] }): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>("/batch_users", data);
  },

  async exportList(params: UserListParams): Promise<Blob> {
    const res = await fetch(`${API_BASE_URL}/users/export?${new URLSearchParams(params as Record<string, string>)}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem("encoach_token") ?? ""}` },
    });
    if (!res.ok) throw new Error(`Export failed: ${res.status} ${res.statusText}`);
    return res.blob();
  },
};
