/** Canned responses: team-wide (agent_id NULL) plus each agent's personal set. */
import { many, one, query } from '../../db/pool.js';
import { notFound } from '../../utils/errors.js';
import type { CannedResponseDTO } from '../types.js';

const toDTO = (r: any): CannedResponseDTO => ({
  id: r.id,
  title: r.title,
  shortcut: r.shortcut ?? null,
  body: r.body,
  scope: r.agent_id ? 'personal' : 'team',
});

export async function listCanned(agentId: string): Promise<CannedResponseDTO[]> {
  const rows = await many(
    `SELECT * FROM canned_responses
      WHERE agent_id IS NULL OR agent_id = $1
      ORDER BY agent_id NULLS FIRST, title ASC`,
    [agentId],
  );
  return rows.map(toDTO);
}

export async function createCanned(input: {
  agentId: string | null;
  title: string;
  shortcut?: string | null;
  body: string;
}): Promise<CannedResponseDTO> {
  const row = await one(
    `INSERT INTO canned_responses (agent_id, title, shortcut, body) VALUES ($1,$2,$3,$4) RETURNING *`,
    [input.agentId, input.title.trim(), input.shortcut?.trim() || null, input.body],
  );
  return toDTO(row);
}

/** Only personal responses are deletable by their owner; team ones need admin. */
export async function deleteCanned(id: string, agentId: string): Promise<void> {
  const res = await query(`DELETE FROM canned_responses WHERE id = $1 AND agent_id = $2`, [id, agentId]);
  if (res.rowCount === 0) throw notFound('Canned response not found, or not yours to delete');
}
