import type { DbClient } from '../db.js';
import { emitSync } from '../socket.js';

export async function recordActivity(
  db: DbClient,
  input: { actorUserId?: string; eventType: string; entityType?: string; entityId?: string; message?: string; metadata?: Record<string, unknown> }
) {
  await db.query(
    `INSERT INTO activity_logs (actor_user_id,event_type,entity_type,entity_id,message,metadata)
     VALUES ($1,$2,$3,$4,$5,$6::jsonb)`,
    [input.actorUserId ?? null, input.eventType, input.entityType ?? null, input.entityId ?? null, input.message ?? null, JSON.stringify(input.metadata ?? {})]
  );
}

export async function recordSyncEvent(
  db: DbClient,
  input: { clientActionId?: string; eventType: string; entityType: string; entityId: string; actorUserId?: string; payload?: Record<string, unknown> }
) {
  const { rows } = await db.query(
    `INSERT INTO sync_events (client_action_id,event_type,entity_type,entity_id,payload,actor_user_id)
     VALUES ($1,$2,$3,$4,$5::jsonb,$6)
     ON CONFLICT (client_action_id) DO NOTHING
     RETURNING sequence,id,event_type,entity_type,entity_id,payload,created_at`,
    [input.clientActionId ?? null, input.eventType, input.entityType, input.entityId, JSON.stringify(input.payload ?? {}), input.actorUserId ?? null]
  );
  if (rows[0]) emitSync(input.eventType, rows[0] as Record<string, unknown>);
  return rows[0] ?? null;
}

export async function notify(
  db: DbClient,
  input: { userId?: string; title: string; body: string; eventType?: string; entityType?: string; entityId?: string }
) {
  await db.query(
    `INSERT INTO notifications (user_id,title,body,event_type,entity_type,entity_id)
     VALUES ($1,$2,$3,$4,$5,$6)`,
    [input.userId ?? null, input.title, input.body, input.eventType ?? null, input.entityType ?? null, input.entityId ?? null]
  );
}
