import { AuditLogProvider, DataProvider } from '@refinedev/core';

export function auditLogProvider(dataProvider: DataProvider): AuditLogProvider {
  return {
    get: async ({ resource, meta }) => {
      const { data } = await dataProvider.getList({
        resource: 'audit',
        filters: [
          {
            field: 'resource',
            operator: 'eq',
            value: resource,
          },
          {
            field: 'resourceId',
            operator: 'eq',
            value: String(meta?.id),
          },
        ],
      });

      return data;
    },
    create: (params) => {
      if (params?.meta?.ids) {
        if (
          ['updateMany', 'createMany'].includes(params.action) &&
          params.data.length === params?.meta?.ids.length
        ) {
          const variables = params.data.map((item: any, index: number) => ({
            action: params.action,
            resource: params.resource,
            resourceId: String(params.meta.ids[index]),
            data: JSON.stringify(item),
            previousData: Array.isArray(params.previousData)
              ? JSON.stringify(params.previousData[index])
              : JSON.stringify(params.previousData),
            authorName: params?.author?.name || '',
            authorId: String(params?.author?.id) || '',
          }));
          if (dataProvider.createMany) {
            return dataProvider.createMany({ resource: 'audit', variables });
          }
          return dataProvider.create({
            resource: 'audit',
            variables: variables[0],
          });
        } else {
          const variables = params.meta.ids.map((id: any) => ({
            action: params.action,
            resource: params.resource,
            resourceId: String(id),
            data: '{}',
            previousData: '{}',
            authorName: params?.author?.name || '',
            authorId: String(params?.author?.id) || '',
          }));
          if (dataProvider.createMany) {
            return dataProvider.createMany({ resource: 'audit', variables });
          }
          return dataProvider.create({
            resource: 'audit',
            variables: variables[0],
          });
        }
      }
      return dataProvider.create({
        resource: 'audit',
        variables: {
          action: params.action,
          resource: params.resource,
          resourceId: params.meta.id || '',
          data: JSON.stringify(params.data),
          previousData: JSON.stringify(params.previousData),
          authorName: params?.author?.name || '',
          authorId: String(params?.author?.id) || '',
        },
      });
    },
    update: async ({ id, name }) => {
      const { data } = await dataProvider.update({
        resource: 'audit',
        id,
        variables: { name },
      });
      return data;
    },
  };
}
