const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
import { fetchWithAuth, postWithAuth, patchWithAuth, deleteWithAuth } from '../fetchWithAuth';

async function handleResponse(response, operation = 'operación') {
  if (response.status === 401) throw new Error('SESSION_EXPIRED');
  if (!response.ok) {
    let detail = `Error ${response.status}`;
    try {
      const body = await response.json();
      detail = body.detail || body.message || JSON.stringify(body);
    } catch {
      detail = await response.text().catch(() => detail);
    }
    throw new Error(detail);
  }
  const contentType = response.headers.get('content-type');
  if (!contentType?.includes('application/json')) return null;
  return response.json();
}

// ── Catálogo de permisos ─────────────────────────────────────────────────────

/** Array plano: [{ id, codename, descripcion, modulo }] */
export async function fetchPermissions() {
  const res = await fetchWithAuth(`${API_URL}/rbac/permissions/`);
  return handleResponse(res, 'Fetch Permissions');
}

/** Agrupado por módulo: { cards: [...], coves: [...], ... } */
export async function fetchPermissionsByModule() {
  const res = await fetchWithAuth(`${API_URL}/rbac/permissions/by-module/`);
  return handleResponse(res, 'Fetch Permissions By Module');
}

// ── Permisos efectivos del usuario actual ────────────────────────────────────

/** { permissions: ["cards.view", ...], roles: ["admin"] } */
export async function fetchMyPermissions() {
  const res = await fetchWithAuth(`${API_URL}/rbac/my-permissions/`);
  return handleResponse(res, 'Fetch My Permissions');
}

// ── Roles (OrganizationRole) ─────────────────────────────────────────────────

export async function fetchRoles() {
  const res = await fetchWithAuth(`${API_URL}/rbac/roles/`);
  return handleResponse(res, 'Fetch Roles');
}

/**
 * data: { nombre, descripcion?, permission_ids: number[] }
 * permission_ids son IDs numéricos de RolePermission.
 */
export async function createRole(data) {
  const res = await postWithAuth(`${API_URL}/rbac/roles/`, data);
  return handleResponse(res, 'Create Role');
}

export async function getRole(id) {
  const res = await fetchWithAuth(`${API_URL}/rbac/roles/${id}/`);
  return handleResponse(res, 'Get Role');
}

/**
 * PATCH — reemplaza el rol completo.
 * data: { nombre?, descripcion?, permission_ids?: number[] }
 */
export async function updateRole(id, data) {
  const res = await patchWithAuth(`${API_URL}/rbac/roles/${id}/`, data);
  return handleResponse(res, 'Update Role');
}

export async function deleteRole(id) {
  const res = await deleteWithAuth(`${API_URL}/rbac/roles/${id}/`);
  if (res.status === 401) throw new Error('SESSION_EXPIRED');
  if (!res.ok) {
    let detail = `Error ${res.status}`;
    try { detail = (await res.json()).detail || detail; } catch {}
    throw new Error(detail);
  }
  return true;
}

// ── Asignación de roles a usuarios (UserRole) ────────────────────────────────

/**
 * userId: filtra por usuario. Usa ?user_id= según spec.
 * Respuesta: [{ id, user: {...}, role: {...}, created_at }]
 */
export async function fetchUserRoles(userId) {
  const url = userId
    ? `${API_URL}/rbac/user-roles/?user_id=${userId}`
    : `${API_URL}/rbac/user-roles/`;
  const res = await fetchWithAuth(url);
  return handleResponse(res, 'Fetch User Roles');
}

/**
 * body: { user_id, role_id } — UUIDs según spec del backend.
 */
export async function assignUserRole(userId, roleId) {
  const res = await postWithAuth(`${API_URL}/rbac/user-roles/`, {
    user_id: userId,
    role_id: roleId,
  });
  return handleResponse(res, 'Assign Role');
}

export async function revokeUserRole(userRoleId) {
  const res = await deleteWithAuth(`${API_URL}/rbac/user-roles/${userRoleId}/`);
  if (res.status === 401) throw new Error('SESSION_EXPIRED');
  if (!res.ok) {
    let detail = `Error ${res.status}`;
    try { detail = (await res.json()).detail || detail; } catch {}
    throw new Error(detail);
  }
  return true;
}

// ── Switch de organización (solo SuperUser) ───────────────────────────────────

/**
 * Establece la organización activa del superuser.
 * body: { organization_id: "uuid" }
 */
export async function switchOrganization(organizationId) {
  const res = await postWithAuth(`${API_URL}/rbac/switch-organization/`, {
    organization_id: organizationId,
  });
  return handleResponse(res, 'Switch Organization');
}

/** Limpia la organización activa del superuser. */
export async function clearOrganization() {
  const res = await deleteWithAuth(`${API_URL}/rbac/switch-organization/`);
  if (res.status === 401) throw new Error('SESSION_EXPIRED');
  if (!res.ok) {
    let detail = `Error ${res.status}`;
    try { detail = (await res.json()).detail || detail; } catch {}
    throw new Error(detail);
  }
  return true;
}

// ── Permisos singulares por usuario (UserPermission) ─────────────────────────

export async function fetchUserPermissions(userId) {
  const url = userId
    ? `${API_URL}/rbac/user-permissions/?user_id=${userId}`
    : `${API_URL}/rbac/user-permissions/`;
  const res = await fetchWithAuth(url);
  return handleResponse(res, 'Fetch User Permissions');
}
