import type { Sql } from '../db.js';
import type { ToolCall } from '../types/api.js';

// Shared lookup for the answer_user_input + grant_read_access pause-resume
// endpoints. Finds the originating assistant tool_call by id in message_parts,
// validates the tool name, finds the pending tool_result part, and checks the
// already-answered guard. Returns ok:true+context on success, ok:false+HTTP
// status+body on any error (caller does reply.code(ctx.code); return ctx.body).
export type PendingToolLookupResult =
  | {
      ok: true;
      foundCall: ToolCall;
      toolMessageId: string;
      toolRow: { message_id: string; payload: { tool_call_id: string; output: unknown } };
    }
  | { ok: false; code: number; body: Record<string, unknown> };

export async function lookupPendingToolCall(
  sql: Sql,
  chatId: string,
  tool_call_id: string,
  expectedToolName: string,
  wrongToolError: string,
): Promise<PendingToolLookupResult> {
  // Find the assistant's tool_call by id via message_parts.
  const callerRows = await sql<{
    message_id: string;
    payload: { id: string; name: string; args: Record<string, unknown> };
  }[]>`
    SELECT p.message_id, p.payload
    FROM message_parts p
    JOIN messages m ON m.id = p.message_id
    WHERE m.chat_id = ${chatId}
      AND m.role = 'assistant'
      AND p.kind = 'tool_call'
      AND p.payload->>'id' = ${tool_call_id}
    ORDER BY m.created_at DESC
    LIMIT 1
  `;
  const callerRow = callerRows[0];
  if (!callerRow) return { ok: false, code: 404, body: { error: 'unknown_tool_call_id' } };

  const foundCall: ToolCall = {
    id: callerRow.payload.id,
    name: callerRow.payload.name,
    args: callerRow.payload.args,
  };
  if (foundCall.name !== expectedToolName) {
    return { ok: false, code: 400, body: { error: wrongToolError } };
  }

  // Find the pending tool_result part by tool_call_id.
  const toolRows = await sql<{
    message_id: string;
    payload: { tool_call_id: string; output: unknown };
  }[]>`
    SELECT p.message_id, p.payload
    FROM message_parts p
    JOIN messages m ON m.id = p.message_id
    WHERE m.chat_id = ${chatId}
      AND m.role = 'tool'
      AND p.kind = 'tool_result'
      AND p.payload->>'tool_call_id' = ${tool_call_id}
    ORDER BY m.created_at DESC
    LIMIT 1
  `;
  const toolRow = toolRows[0];
  if (!toolRow) {
    return { ok: false, code: 404, body: { error: 'unknown_tool_call_id', detail: 'tool message not found' } };
  }
  if (toolRow.payload && toolRow.payload.output !== null) {
    return { ok: false, code: 409, body: { error: 'tool_call_already_answered' } };
  }

  return { ok: true, foundCall, toolMessageId: toolRow.message_id, toolRow };
}
