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

export const entitiesService = {
  async list(params?: PaginationParams): Promise<PaginatedResponse<Entity>> {
    const raw = await api.get<unknown>("/entities", params as Record<string, string | number | boolean | undefined>);
    return asPaginated<Entity>(raw);
  },

  async getById(id: number): Promise<Entity> {
    const raw = await api.get<unknown>(`/entities/${id}`);
    return asRecordData<Entity>(raw);
  },

  async create(data: Partial<Entity>): Promise<Entity> {
    const raw = await api.post<unknown>("/entities", data);
    return asRecordData<Entity>(raw);
  },

  async update(id: number, data: Partial<Entity>): Promise<Entity> {
    const raw = await api.patch<unknown>(`/entities/${id}`, data);
    return asRecordData<Entity>(raw);
  },

  async delete(id: number): Promise<ApiSuccessResponse> {
    return api.delete<ApiSuccessResponse>(`/entities/${id}`);
  },

  async getRoles(entityId: number): Promise<EntityRole[]> {
    return api.get<EntityRole[]>(`/entities/${entityId}/roles`);
  },

  async createRole(entityId: number, data: Partial<EntityRole>): Promise<EntityRole> {
    return api.post<EntityRole>(`/entities/${entityId}/roles`, data);
  },

  async updateRolePermissions(roleId: number, permissions: string[]): Promise<EntityRole> {
    return api.patch<EntityRole>(`/roles/${roleId}/permissions`, { permissions });
  },

  async getPermissions(entityId: number): Promise<string[]> {
    return api.get<string[]>(`/permissions`, { entity_id: entityId });
  },
};
