// ═══════════════════════════════════════════════════
//  app/lib/api/user.api.ts
// ═══════════════════════════════════════════════════

import { fetchApi, API_BASE_URL } from "./http";
import {
  UserRaw,
  RoleRaw,
  CreateUserDto,
  UpdateUserDto,
  AssignRolesDto,
} from "./../api/types/user.types";

// ── Users ────────────────────────────────────────────

/** GET /users — list all users with roles & permissions */
export const getUsers = async (): Promise<UserRaw[]> => {
  return fetchApi<UserRaw[]>(`${API_BASE_URL}/users`);
};

/** GET /users/:id — single user */
export const getUserById = async (id: number): Promise<UserRaw> => {
  return fetchApi<UserRaw>(`${API_BASE_URL}/users/${id}`);
};

/** POST /auth/register — create new user (sends OTP email) */
export const createUser = async (dto: CreateUserDto): Promise<{ message: string; email: string }> => {
  return fetchApi<{ message: string; email: string }>(`${API_BASE_URL}/auth/register`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
};

/** PATCH /auth/update/:id — update user profile */
export const updateUser = async (
  id: number,
  dto: UpdateUserDto,
): Promise<{ message: string; user: UserRaw }> => {
  // Remove empty password from payload
  const payload = { ...dto };
  if (!payload.password) delete payload.password;

  return fetchApi<{ message: string; user: UserRaw }>(`${API_BASE_URL}/auth/update/${id}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
};

/** DELETE /users/:id — delete user */
export const deleteUser = async (id: number): Promise<void> => {
  return fetchApi<void>(`${API_BASE_URL}/users/${id}`, {
    method: "DELETE",
  });
};

// ── Admin Actions ────────────────────────────────────

/** PATCH /auth/approve/:id — approve pending user */
export const approveUser = async (id: number): Promise<{ message: string }> => {
  return fetchApi<{ message: string }>(`${API_BASE_URL}/auth/approve/${id}`, {
    method: "PATCH",
  });
};

/** PATCH /auth/reject/:id — reject pending user */
export const rejectUser = async (id: number): Promise<{ message: string }> => {
  return fetchApi<{ message: string }>(`${API_BASE_URL}/auth/reject/${id}`, {
    method: "PATCH",
  });
};
// ✅ ADD HERE — after rejectUser
/** PATCH /auth/update/:id — admin manually verify user email */
export const verifyUserEmail = async (id: number): Promise<{ message: string }> => {
  return fetchApi<{ message: string }>(`${API_BASE_URL}/auth/update/${id}`, {
    method: "PATCH",
    body: JSON.stringify({ isEmailVerified: true, status: "pending" }),
  });
};

/** GET /auth/pending-users — get pending users awaiting approval */
export const getPendingUsers = async (): Promise<UserRaw[]> => {
  return fetchApi<UserRaw[]>(`${API_BASE_URL}/auth/pending-users`);
};

// ── Role Assignment ──────────────────────────────────

/** POST /users/:id/assign-roles — assign roles to user */
/** POST /users/assign-roles — assign roles to user */
export const assignUserRoles = async (
  userId: number,
  dto: AssignRolesDto,
): Promise<UserRaw> => {
  return fetchApi<UserRaw>(`${API_BASE_URL}/users/assign-roles`, {
    method: "POST",
    body: JSON.stringify({ userId, ...dto }),
  });
};

// ── Roles ────────────────────────────────────────────

/** GET /roles — list all roles */
export const getRoles = async (): Promise<RoleRaw[]> => {
  return fetchApi<RoleRaw[]>(`${API_BASE_URL}/roles`);
};
