import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBType } from "@tailor-platform/sdk";

export interface CreateAuditEntryTypeParams {
  companyType?: TailorAnyDBType;
}

export function createAuditEntryType(params: CreateAuditEntryTypeParams) {
  const companyId = db
    .uuid({ optional: true })
    .description("Foreign key to Company; null for global entities");
  return db
    .type("AuditEntry", {
      eventId: db.uuid().unique().description("Globally unique event ID for idempotency"),
      actorType: db.string().description("Actor type: USER, SYSTEM, or SERVICE"),
      actorId: db.string().description("Actor identifier"),
      entityType: db.string().description("Type name of the audited entity"),
      entityId: db.string().description("ID of the audited entity"),
      operationType: db.string().description("Operation type: CREATE, UPDATE, or DELETE"),
      companyId: params.companyType
        ? companyId.relation({
            type: "keyOnly",
            toward: { type: params.companyType },
            backward: "auditEntries",
          })
        : companyId,
      correlationId: db
        .uuid({ optional: true })
        .description("Optional correlation ID grouping related events"),
      ipAddress: db.string({ optional: true }).description("Actor IP address metadata"),
      userAgent: db.string({ optional: true }).description("Actor user agent metadata"),
      sessionId: db.string({ optional: true }).description("Actor session ID metadata"),
      requestId: db.string({ optional: true }).description("Request ID metadata"),
      onBehalfOf: db
        .string({ optional: true })
        .description("Delegated user identity when acting on behalf of another"),
      timestamp: db.date().description("System-generated timestamp at ingestion time"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const auditEntry = createAuditEntryType({});
