import { PipedriveClient, err } from "../client.js";
import type { ToolDefinition, ToolResult, Deal } from "../types.js";

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_app_deal_detail",
    description: "Full deal view with products, activities, participants, and timeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Deal ID" },
      },
      required: ["id"],
    },
  },
];

function escapeHtml(s: string | undefined): string {
  return (s || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    const dealResult = await client.get<{ success: boolean; data: Deal }>(`/deals/${args.id}`);
    const deal = dealResult.data;

    const activitiesResult = await client.get<{ success: boolean; data: unknown[] }>(`/deals/${args.id}/activities`);
    const activities = activitiesResult.data || [];

    const filesResult = await client.get<{ success: boolean; data: unknown[] }>(`/deals/${args.id}/files`);
    const files = filesResult.data || [];

    const html = `
      <div style="font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#0d0d1a;color:#e0e0e0;padding:24px;border-radius:16px;max-width:1000px;">
        <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:24px;">
          <div>
            <h2 style="margin:0 0 8px;color:#fff;">${escapeHtml(deal.title)}</h2>
            <div style="font-size:13px;color:#666;">ID: ${deal.id} • ${deal.status}</div>
          </div>
          <div style="text-align:right;">
            <div style="font-size:32px;font-weight:600;color:#4CAF50;">${(deal.value || 0).toLocaleString()} ${deal.currency}</div>
            <div style="font-size:12px;color:#888;">${deal.probability || 0}% probability</div>
          </div>
        </div>

        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px;">
          <div style="background:#1a1a2e;padding:16px;border-radius:8px;">
            <div style="font-size:11px;color:#888;margin-bottom:4px;">Pipeline Stage</div>
            <div style="font-size:15px;font-weight:500;">Stage ${deal.stage_id}</div>
          </div>
          <div style="background:#1a1a2e;padding:16px;border-radius:8px;">
            <div style="font-size:11px;color:#888;margin-bottom:4px;">Expected Close</div>
            <div style="font-size:15px;font-weight:500;">${deal.expected_close_date || "Not set"}</div>
          </div>
          <div style="background:#1a1a2e;padding:16px;border-radius:8px;">
            <div style="font-size:11px;color:#888;margin-bottom:4px;">Owner</div>
            <div style="font-size:15px;font-weight:500;">User ${deal.user_id || "N/A"}</div>
          </div>
        </div>

        <h3 style="color:#ccc;margin:24px 0 12px;font-size:16px;">📅 Activities (${activities.length})</h3>
        <div style="background:#1a1a2e;padding:16px;border-radius:8px;margin-bottom:24px;min-height:60px;">
          ${activities.length > 0 ? `<div style="font-size:13px;color:#888;">${activities.length} activities found</div>` : `<div style="font-size:13px;color:#666;">No activities yet</div>`}
        </div>

        <h3 style="color:#ccc;margin:24px 0 12px;font-size:16px;">📎 Files (${files.length})</h3>
        <div style="background:#1a1a2e;padding:16px;border-radius:8px;min-height:60px;">
          ${files.length > 0 ? `<div style="font-size:13px;color:#888;">${files.length} files attached</div>` : `<div style="font-size:13px;color:#666;">No files attached</div>`}
        </div>
      </div>
    `;

    return {
      content: [{ type: "text", text: `Deal details for ${deal.title}` }],
      structuredContent: { type: "html", html },
    };
  } catch (error) {
    return err(error);
  }
}
