import { apiClient } from '@/lib/api-client';
import type {
  PermissionAuditLogFilters,
  PermissionAuditLogsResponse,
  PermissionCatalogResponse,
  PermissionTemplateFilters,
  PermissionTemplateMutationPayload,
  PermissionTemplatesResponse,
  UserPermissionAssignmentDetail,
  UserPermissionAssignmentFilters,
  UserPermissionAssignmentMutationPayload,
  UserPermissionAssignmentsResponse,
  UserPermissionOverrideMutationPayload
} from './types';

function createQueryString<T extends object>(filters: T) {
  const params = new URLSearchParams();

  for (const [key, value] of Object.entries(filters as Record<string, unknown>)) {
    if (value !== undefined && value !== null && value !== '') {
      params.set(key, String(value));
    }
  }

  return params.toString();
}

export async function getPermissionTemplates(
  filters: PermissionTemplateFilters
): Promise<PermissionTemplatesResponse> {
  const queryString = createQueryString(filters);
  return apiClient<PermissionTemplatesResponse>(
    `/permission-templates${queryString ? `?${queryString}` : ''}`
  );
}

export async function getPermissionCatalog(): Promise<PermissionCatalogResponse> {
  return apiClient<PermissionCatalogResponse>('/permissions/catalog');
}

export async function createPermissionTemplate(data: PermissionTemplateMutationPayload) {
  return apiClient<{ success: boolean; message: string; template_id: number }>('/permission-templates', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function getPermissionTemplate(id: number) {
  return apiClient<{ success: boolean; permission_template: PermissionTemplatesResponse['permission_templates'][number] }>(
    `/permission-templates/${id}`
  );
}

export async function updatePermissionTemplate(
  id: number,
  data: PermissionTemplateMutationPayload
) {
  return apiClient<{ success: boolean; message: string }>(`/permission-templates/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deletePermissionTemplate(id: number, reason?: string) {
  return apiClient<{ success: boolean; message: string }>(`/permission-templates/${id}`, {
    method: 'DELETE',
    body: JSON.stringify({ reason })
  });
}

export async function clonePermissionTemplate(id: number, reason?: string) {
  return apiClient<{ success: boolean; message: string; template_id: number }>(
    `/permission-templates/${id}/clone`,
    {
      method: 'POST',
      body: JSON.stringify({ reason })
    }
  );
}

export async function activatePermissionTemplate(id: number, reason?: string) {
  return apiClient<{ success: boolean; message: string }>(`/permission-templates/${id}/activate`, {
    method: 'POST',
    body: JSON.stringify({ reason })
  });
}

export async function deactivatePermissionTemplate(id: number, reason?: string) {
  return apiClient<{ success: boolean; message: string }>(`/permission-templates/${id}/deactivate`, {
    method: 'POST',
    body: JSON.stringify({ reason })
  });
}

export async function getUserPermissionAssignments(
  filters: UserPermissionAssignmentFilters
): Promise<UserPermissionAssignmentsResponse> {
  const queryString = createQueryString(filters);
  return apiClient<UserPermissionAssignmentsResponse>(
    `/user-permissions${queryString ? `?${queryString}` : ''}`
  );
}

export async function getUserPermissionAssignmentDetail(
  userId: string
): Promise<{ success: boolean; detail: UserPermissionAssignmentDetail }> {
  return apiClient<{ success: boolean; detail: UserPermissionAssignmentDetail }>(
    `/user-permissions/${userId}`
  );
}

export async function saveUserPermissionAssignment(
  userId: string,
  data: UserPermissionAssignmentMutationPayload
) {
  return apiClient<{ success: boolean; message: string }>(`/user-permissions/${userId}/assignment`, {
    method: 'PUT',
    body: JSON.stringify(data)
  });
}

export async function createUserPermissionOverride(
  userId: string,
  data: UserPermissionOverrideMutationPayload
) {
  return apiClient<{ success: boolean; message: string; override_id: number }>(
    `/user-permissions/${userId}/overrides`,
    {
      method: 'POST',
      body: JSON.stringify(data)
    }
  );
}

export async function updateUserPermissionOverride(
  userId: string,
  overrideId: number,
  data: UserPermissionOverrideMutationPayload
) {
  return apiClient<{ success: boolean; message: string }>(
    `/user-permissions/${userId}/overrides/${overrideId}`,
    {
      method: 'PATCH',
      body: JSON.stringify(data)
    }
  );
}

export async function deleteUserPermissionOverride(userId: string, overrideId: number) {
  return apiClient<{ success: boolean; message: string }>(
    `/user-permissions/${userId}/overrides/${overrideId}`,
    {
      method: 'DELETE'
    }
  );
}

export async function getPermissionAuditLogs(
  filters: PermissionAuditLogFilters
): Promise<PermissionAuditLogsResponse> {
  const queryString = createQueryString(filters);
  return apiClient<PermissionAuditLogsResponse>(
    `/permission-audit-logs${queryString ? `?${queryString}` : ''}`
  );
}
