import { z } from 'zod';
import { eq } from 'drizzle-orm';
import { order, orderLine, dealSkus } from '@/server/db/schema.js';
import { lineRedemptionStatusSql } from '@/server/fulfillment/voucher-line-state.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';

const inputSchema = z.object({ id: z.uuid() });

type Output = {
  id: string;
  status: string;
  dealTitle: string;
  amountCents: number | null;
  redemptionStatus: 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 [row] = await deps.db
    .select({
      id: orderLine.id,
      orderStatus: order.status,
      lineTotal: orderLine.lineTotal,
      dealId: dealSkus.dealId,
      redemptionStatus: lineRedemptionStatusSql(orderLine.id),
    })
    .from(orderLine)
    .innerJoin(order, eq(orderLine.orderId, order.id))
    .innerJoin(dealSkus, eq(orderLine.variantId, dealSkus.id))
    .where(eq(orderLine.id, parsed.data.id))
    .limit(1);

  if (!row) return { ok: false, error: 'NOT_FOUND:purchase' };

  return {
    ok: true,
    data: {
      id: row.id,
      status: row.orderStatus,
      dealTitle: `deal:${row.dealId}`, // PII-safe — no vendor name; Phase 6 can enrich
      amountCents: Number(row.lineTotal), // lineTotal already in agorot
      redemptionStatus: row.redemptionStatus ?? 'unredeemed',
    },
  };
}

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