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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_subscriptions_list",
    description: "List all subscriptions (recurring revenue)",
    inputSchema: {
      type: "object",
      properties: {
        deal_id: { type: "number", description: "Filter by deal" },
      },
    },
  },
  {
    name: "pipedrive_subscription_get",
    description: "Get a single subscription by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Subscription ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_subscription_create",
    description: "Create a new subscription",
    inputSchema: {
      type: "object",
      properties: {
        deal_id: { type: "number", description: "Deal ID" },
        currency: { type: "string", description: "Currency code" },
        cadence_type: { type: "string", description: "weekly, monthly, quarterly, yearly" },
        cycle_amount: { type: "number", description: "Amount per cycle" },
        start_date: { type: "string", description: "Start date (YYYY-MM-DD)" },
        end_date: { type: "string", description: "End date (YYYY-MM-DD)" },
        cycles_count: { type: "number", description: "Number of billing cycles" },
        infinite: { type: "boolean", description: "Infinite subscription" },
      },
      required: ["deal_id", "currency", "cadence_type", "cycle_amount", "start_date"],
    },
  },
  {
    name: "pipedrive_subscription_update",
    description: "Update an existing subscription",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Subscription ID" },
        cycle_amount: { type: "number" },
        end_date: { type: "string" },
        cycles_count: { type: "number" },
        is_active: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_subscription_cancel",
    description: "Cancel a subscription",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Subscription ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_subscriptions_list": {
        const params: Record<string, unknown> = {};
        if (args.deal_id) params.deal_id = args.deal_id;

        const result = await client.get<{ success: boolean; data: Subscription[] }>("/subscriptions", params);
        const subs = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${subs.length} subscriptions:\n${subs.map((s) => `- [${s.id}] Deal ${s.deal_id}: ${s.cycle_amount} ${s.currency} ${s.cadence_type} (${s.is_active ? "active" : "inactive"})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_subscription_get": {
        const result = await client.get<{ success: boolean; data: Subscription }>(`/subscriptions/${args.id}`);
        const sub = result.data;
        return {
          content: [{
            type: "text",
            text: `Subscription ID: ${sub.id}\nDeal ID: ${sub.deal_id}\nAmount: ${sub.cycle_amount} ${sub.currency} ${sub.cadence_type}\nActive: ${sub.is_active ? "Yes" : "No"}\nStart: ${sub.start_date}\nEnd: ${sub.end_date || "N/A"}\nLifetime value: ${sub.lifetime_value || "N/A"}`,
          }],
        };
      }

      case "pipedrive_subscription_create": {
        const result = await client.post<{ success: boolean; data: Subscription }>("/subscriptions", args);
        const sub = result.data;
        return {
          content: [{ type: "text", text: `Created subscription: ${sub.cycle_amount} ${sub.currency} ${sub.cadence_type} (ID: ${sub.id})` }],
        };
      }

      case "pipedrive_subscription_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: Subscription }>(`/subscriptions/${id}`, updateData);
        const sub = result.data;
        return {
          content: [{ type: "text", text: `Updated subscription (ID: ${sub.id})` }],
        };
      }

      case "pipedrive_subscription_cancel": {
        const result = await client.put<{ success: boolean; data: Subscription }>(`/subscriptions/${args.id}`, { is_active: false });
        return {
          content: [{ type: "text", text: `Cancelled subscription ${args.id}` }],
        };
      }

      default:
        return {
          content: [{ type: "text", text: `Unknown tool: ${name}` }],
          isError: true,
        };
    }
  } catch (error) {
    return err(error);
  }
}
