import { apiClient } from "./client";

export interface AuditLogEntry {
  id: number;
  company_code: string;
  company_name: string | null;
  user_id: string;
  user_name: string | null;
  action: string;
  resource_type: string;
  resource_id: string | null;
  resource_name: string | null;
  table_name: string | null;
  summary: string | null;
  changes: any;
  ip_address: string | null;
  request_path: string | null;
  created_at: string;
}

export interface AuditLogFilters {
  companyCode?: string;
  userId?: string;
  resourceType?: string;
  action?: string;
  tableName?: string;
  dateFrom?: string;
  dateTo?: string;
  search?: string;
  page?: number;
  limit?: number;
}

export interface AuditLogStats {
  dailyCounts: Array<{ date: string; count: number }>;
  resourceTypeCounts: Array<{ resource_type: string; count: number }>;
  actionCounts: Array<{ action: string; count: number }>;
  topUsers: Array<{ user_id: string; user_name: string; count: number }>;
}

export async function getAuditLogs(
  filters: AuditLogFilters
): Promise<{
  success: boolean;
  data: AuditLogEntry[];
  total: number;
  page: number;
  limit: number;
}> {
  const params = new URLSearchParams();
  if (filters.companyCode) params.append("companyCode", filters.companyCode);
  if (filters.userId) params.append("userId", filters.userId);
  if (filters.resourceType) params.append("resourceType", filters.resourceType);
  if (filters.action) params.append("action", filters.action);
  if (filters.tableName) params.append("tableName", filters.tableName);
  if (filters.dateFrom) params.append("dateFrom", filters.dateFrom);
  if (filters.dateTo) params.append("dateTo", filters.dateTo);
  if (filters.search) params.append("search", filters.search);
  if (filters.page) params.append("page", String(filters.page));
  if (filters.limit) params.append("limit", String(filters.limit));

  const response = await apiClient.get(`/audit-log?${params.toString()}`);
  return response.data;
}

export async function getAuditLogStats(
  companyCode?: string,
  days?: number
): Promise<{ success: boolean; data: AuditLogStats }> {
  const params = new URLSearchParams();
  if (companyCode) params.append("companyCode", companyCode);
  if (days) params.append("days", String(days));

  const response = await apiClient.get(`/audit-log/stats?${params.toString()}`);
  return response.data;
}

export interface AuditLogUser {
  user_id: string;
  user_name: string;
  count: number;
}

export async function getAuditLogUsers(
  companyCode?: string
): Promise<{ success: boolean; data: AuditLogUser[] }> {
  const params = new URLSearchParams();
  if (companyCode) params.append("companyCode", companyCode);

  const response = await apiClient.get(`/audit-log/users?${params.toString()}`);
  return response.data;
}
