import { z } from 'zod';
import * as caseQ from '@/server/db/queries/support-cases.js';
import * as offersQ from '@/server/db/queries/case-offers.js';
import * as transitionsQ from '@/server/db/queries/support-state-transitions.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';
import { asCaseId } from '@/server/platform-seams/ids.js';

const inputSchema = z.object({
  caseId: z.uuid(),
  outcome: z.enum(['refund_full', 'refund_partial', 'replacement', 'deny']),
  amountCents: z.number().int().nonnegative().optional(),
  reason: z.string().min(1).max(1000),
});

type Output = { offerId: string };

async function impl(deps: AgentDeps, rawInput: unknown): Promise<ToolResult<Output>> {
  const parsed = inputSchema.safeParse(rawInput);
  if (!parsed.success) return { ok: false, error: `INVALID_INPUT:${parsed.error.message}` };

  const { outcome, amountCents, reason } = parsed.data;
  const caseId = asCaseId(parsed.data.caseId);

  const c = await caseQ.findById(deps.db, caseId);
  if (!c) return { ok: false, error: 'NOT_FOUND:case' };

  if (c.status !== 'ai_handling' && c.status !== 'awaiting_info') {
    return { ok: false, error: 'AUTONOMY_GATE:status_not_ai_handling_or_awaiting_info' };
  }

  // Supersede any prior pending offers
  const existing = await offersQ.listByCase(deps.db, caseId);
  for (const o of existing.filter((x) => x.status === 'pending')) {
    await offersQ.markSuperseded(deps.db, o.id);
  }

  const offer = await offersQ.insert(deps.db, {
    caseId,
    offeredBy: 'ai',
    outcome,
    amountCents: amountCents ?? null,
    reason,
    status: 'pending',
  });

  // Record state transition for observability
  await transitionsQ.insert(deps.db, {
    parentType: 'case',
    parentId: caseId,
    fromState: c.status,
    toState: c.status, // stays in same status — just records the proposal
    actorType: 'ai',
    actorId: null,
    reason: `propose_resolution:${outcome}`,
    metadata: { offerId: offer.id, amountCents: amountCents ?? null },
  });

  deps.runState.decision = 'propose';

  return { ok: true, data: { offerId: offer.id } };
}

export const proposeResolutionTool = {
  name: 'propose_resolution',
  inputSchema,
  impl,
} satisfies SupportTool<'propose_resolution', z.infer<typeof inputSchema>, Output>;
