import { apiClient } from '../api/api-client';
import type { SecurityRepository } from '@/domain/repositories/security.repository';
import type { RiskRule } from '@/domain/entities/risk-rule';
import type { Credential } from '@/domain/entities/credential';
import type { Role } from '@/domain/entities/role';

export const apiSecurityRepository: SecurityRepository = {
  async listRiskRules(params) {
    const query = params ? '?' + new URLSearchParams(params).toString() : '';
    return apiClient<RiskRule[]>(`/api/v1/agent/risk-rules${query}`);
  },

  async getRiskRuleById(id) {
    return apiClient<RiskRule>(`/api/v1/agent/risk-rules/${id}`);
  },

  async createRiskRule(rule) {
    return apiClient<RiskRule>('/api/v1/agent/risk-rules', {
      method: 'POST',
      body: rule,
    });
  },

  async updateRiskRule(id, data) {
    return apiClient<RiskRule>(`/api/v1/agent/risk-rules/${id}`, {
      method: 'PUT',
      body: data,
    });
  },

  async removeRiskRule(id) {
    await apiClient(`/api/v1/agent/risk-rules/${id}`, {
      method: 'DELETE',
    });
  },

  async listCredentials(params) {
    const query = params ? '?' + new URLSearchParams(params).toString() : '';
    return apiClient<Credential[]>(`/api/v1/inventory/credentials${query}`);
  },

  async getCredentialById(id) {
    return apiClient<Credential>(`/api/v1/inventory/credentials/${id}`);
  },

  async createCredential(credential) {
    return apiClient<Credential>('/api/v1/inventory/credentials', {
      method: 'POST',
      body: credential,
    });
  },

  async updateCredential(id, data) {
    return apiClient<Credential>(`/api/v1/inventory/credentials/${id}`, {
      method: 'PUT',
      body: data,
    });
  },

  async removeCredential(id) {
    await apiClient(`/api/v1/inventory/credentials/${id}`, {
      method: 'DELETE',
    });
  },

  async listRoles() {
    return apiClient<Role[]>('/api/v1/auth/roles');
  },

  async getPermissionMatrix() {
    return apiClient<{ roles: Role[]; allPermissions: string[] }>('/api/v1/auth/permissions/matrix');
  },

  async updateRolePermissions(roleId, permissions) {
    await apiClient(`/api/v1/auth/roles/${roleId}/permissions`, {
      method: 'PUT',
      body: { permissions },
    });
  },
};
