import api from './api';

export interface AuditLog {
    id: string;
    userId?: string;
    userName?: string;
    action: 'CREATE' | 'UPDATE' | 'DELETE' | 'LOGIN' | 'LOGOUT' | 'ACCESS' | 'EXPORT' | 'APPROVE' | 'REJECT';
    entity: string;
    entityId?: string;
    entityName?: string;
    before?: any;
    after?: any;
    changes?: any;
    metadata?: any;
    ipAddress?: string;
    userAgent?: string;
    timestamp: string;
}

export interface AuditLogSummary {
    totalLogs: number;
    byAction: Record<string, number>;
    byEntity: { entity: string; count: number }[];
    recentActivity: {
        id: string;
        action: string;
        entity: string;
        entityName?: string;
        userName?: string;
        timestamp: string;
    }[];
}

export interface AuditLogFilters {
    userId?: string;
    entity?: string;
    entityId?: string;
    action?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    limit?: number;
}

export interface PaginatedAuditLogs {
    logs: AuditLog[];
    pagination: {
        page: number;
        limit: number;
        total: number;
        pages: number;
    };
}

export const auditApi = {
    async getLogs(filters?: AuditLogFilters): Promise<PaginatedAuditLogs> {
        const response = await api.get('/audit/logs', { params: filters });
        return response.data;
    },

    async getLog(id: string): Promise<AuditLog> {
        const response = await api.get(`/audit/logs/${id}`);
        return response.data;
    },

    async getEntityHistory(entity: string, entityId: string): Promise<{
        entity: string;
        entityId: string;
        history: AuditLog[];
    }> {
        const response = await api.get(`/audit/entity/${entity}/${entityId}`);
        return response.data;
    },

    async getUserActivity(userId: string, limit?: number): Promise<{
        userId: string;
        activityLog: AuditLog[];
    }> {
        const response = await api.get(`/audit/user/${userId}`, { params: { limit } });
        return response.data;
    },

    async getSummary(startDate?: string, endDate?: string): Promise<AuditLogSummary> {
        const response = await api.get('/audit/summary', { params: { startDate, endDate } });
        return response.data;
    },

    async exportCsv(filters?: { entity?: string; startDate?: string; endDate?: string }): Promise<Blob> {
        const response = await api.get('/audit/export', {
            params: filters,
            responseType: 'blob'
        });
        return response.data;
    }
};

