import { Injectable } from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { AuditAction, AuditEntityType } from '@aechr/shared';
import { PrismaService } from '../prisma/prisma.service';

interface CreateAuditEntryInput {
  module: string;
  action: AuditAction;
  entityType: AuditEntityType;
  entityId: string;
  oldValues?: Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput;
  newValues?: Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput;
  remarks?: string | null;
  ipAddress?: string | null;
  userAgent?: string | null;
  createdBy?: string | null;
  updatedBy?: string | null;
  deletedBy?: string | null;
}

@Injectable()
export class AuditService {
  constructor(private readonly prisma: PrismaService) {}

  async log(input: CreateAuditEntryInput) {
    return this.prisma.auditLog.create({
      data: {
        module: input.module,
        action: input.action,
        entityType: input.entityType,
        entityId: input.entityId,
        oldValuesJson: input.oldValues,
        newValuesJson: input.newValues,
        remarks: input.remarks ?? null,
        ipAddress: input.ipAddress ?? null,
        userAgent: input.userAgent ?? null,
        createdBy: input.createdBy ?? null,
        updatedBy: input.updatedBy ?? null,
        deletedBy: input.deletedBy ?? null,
      },
    });
  }
}
