import { sql } from '../db.js';
import type { AuditActorType } from '@wa-ticketing/shared';

export const auditService = {
  async log(
    actorId: string | null,
    actorType: AuditActorType,
    action: string,
    entityType: string,
    entityId: string,
    metadata: Record<string, unknown>,
  ): Promise<void> {
    await sql`
      INSERT INTO audit_logs (actor_id, actor_type, action, entity_type, entity_id, metadata)
      VALUES (${actorId}, ${actorType}, ${action}, ${entityType}, ${entityId}, ${sql.json(metadata as never)})
    `;
  },

  async query(filters: {
    actorId?: string;
    action?: string;
    entityType?: string;
    entityId?: string;
    from?: string;
    to?: string;
    limit?: number;
    offset?: number;
  }) {
    const { actorId, action, entityType, entityId, from, to, limit = 50, offset = 0 } = filters;

    return sql`
      SELECT al.*, u.email AS actor_email
      FROM audit_logs al
      LEFT JOIN users u ON u.id = al.actor_id
      WHERE TRUE
        ${actorId    ? sql`AND al.actor_id    = ${actorId}`    : sql``}
        ${action     ? sql`AND al.action      = ${action}`     : sql``}
        ${entityType ? sql`AND al.entity_type = ${entityType}` : sql``}
        ${entityId   ? sql`AND al.entity_id   = ${entityId}`   : sql``}
        ${from       ? sql`AND al.created_at >= ${from}`       : sql``}
        ${to         ? sql`AND al.created_at <= ${to}`         : sql``}
      ORDER BY al.created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `;
  },
};
