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/security/risk-rules${query}`);
  },

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

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

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

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

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

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

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

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

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

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

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

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