import { prisma } from '@/db';
import { AuditWhereInput } from '@/generated/prisma/models';
import { parseError } from '@lib/errors';
import { authMiddleware } from '@lib/middleware';
import { createServerFn } from '@tanstack/react-start';
import { auditListSchema } from './audit.schema';

export const getAllAudit = createServerFn({ method: 'GET' })
  .middleware([authMiddleware])
  .validator(auditListSchema)
  .handler(async ({ data }) => {
    try {
      const skip = (data.page - 1) * data.limit;

      const where: AuditWhereInput = {
        OR: [
          {
            oldValue: {
              contains: data.keyword,
              mode: 'insensitive',
            },
          },
          {
            newValue: {
              contains: data.keyword,
              mode: 'insensitive',
            },
          },
          {
            action: {
              contains: data.keyword,
              mode: 'insensitive',
            },
          },
        ],
      };
      const [auditlog, total]: [AuditWithUser[], number] =
        await prisma.$transaction([
          prisma.audit.findMany({
            where,
            orderBy: { createdAt: 'desc' },
            include: {
              user: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
            take: data.limit,
            skip,
          }),
          prisma.audit.count({ where }),
        ]);

      const totalPage = Math.ceil(+total / data.limit);

      return {
        result: auditlog,
        pagination: {
          currentPage: data.page,
          totalPage,
          totalItem: total,
        },
      };
    } catch (error) {
      console.error(error);
      const { message, code } = parseError(error);
      throw { message, code };
    }
  });
