import { getContainer } from '../../lib/cosmos-init.js';
import { productId } from '../../lib/config.js';
import type { AuditLog, CreateAuditLog } from './types.js';

const AUDIT_LOGS_CONTAINER = 'audit-logs';

export async function createAuditLog(data: CreateAuditLog): Promise<AuditLog> {
  const auditLog: AuditLog = {
    id: `audit-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
    timestamp: new Date().toISOString(),
    ...data,
  };

  await getContainer(AUDIT_LOGS_CONTAINER).items.create(auditLog);
  return auditLog;
}

export async function getAuditLogs(limit = 100): Promise<AuditLog[]> {
  const { resources } = await getContainer(AUDIT_LOGS_CONTAINER)
    .items.query({
      query: 'SELECT * FROM c WHERE c.productId = @productId ORDER BY c.timestamp DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@productId', value: productId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();

  return resources as AuditLog[];
}

export async function getAuditLogsByEntity(entityType: string, entityId: string, limit = 50): Promise<AuditLog[]> {
  const { resources } = await getContainer(AUDIT_LOGS_CONTAINER)
    .items.query({
      query: 'SELECT * FROM c WHERE c.productId = @productId AND c.entityType = @entityType AND c.entityId = @entityId ORDER BY c.timestamp DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@productId', value: productId },
        { name: '@entityType', value: entityType },
        { name: '@entityId', value: entityId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();

  return resources as AuditLog[];
}

export async function getAuditLogsByUser(userId: string, limit = 50): Promise<AuditLog[]> {
  const { resources } = await getContainer(AUDIT_LOGS_CONTAINER)
    .items.query({
      query: 'SELECT * FROM c WHERE c.productId = @productId AND c.userId = @userId ORDER BY c.timestamp DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@productId', value: productId },
        { name: '@userId', value: userId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();

  return resources as AuditLog[];
}
