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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_products_list",
    description: "List all products",
    inputSchema: {
      type: "object",
      properties: {
        user_id: { type: "number", description: "Filter by owner" },
        filter_id: { type: "number" },
        start: { type: "number" },
        limit: { type: "number" },
      },
    },
  },
  {
    name: "pipedrive_product_get",
    description: "Get a single product by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_product_create",
    description: "Create a new product",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Product name" },
        code: { type: "string", description: "Product code/SKU" },
        unit: { type: "string", description: "Unit type (e.g., pcs, hours)" },
        tax: { type: "number", description: "Tax percentage" },
        owner_id: { type: "number", description: "Owner user ID" },
        prices: { type: "string", description: "JSON array of prices" },
        visible_to: { type: "string", description: "Visibility: 1, 3, 5, 7" },
      },
      required: ["name"],
    },
  },
  {
    name: "pipedrive_product_update",
    description: "Update an existing product",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
        name: { type: "string" },
        code: { type: "string" },
        unit: { type: "string" },
        tax: { type: "number" },
        prices: { type: "string", description: "JSON array of prices" },
        active_flag: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_product_delete",
    description: "Delete a product",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_products_search",
    description: "Search products by term",
    inputSchema: {
      type: "object",
      properties: {
        term: { type: "string", description: "Search term" },
        exact_match: { type: "boolean" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["term"],
    },
  },
  {
    name: "pipedrive_product_deals",
    description: "List all deals for a product",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_product_files",
    description: "List all files for a product",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_product_followers",
    description: "List all followers for a product",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Product ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_products_list": {
        const params: Record<string, unknown> = {};
        if (args.user_id) params.user_id = args.user_id;
        if (args.filter_id) params.filter_id = args.filter_id;
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: Product[] }>("/products", params);
        const products = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${products.length} products\n${products.map((p) => `- [${p.id}] ${p.name} (code: ${p.code || "N/A"})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_product_get": {
        const result = await client.get<{ success: boolean; data: Product }>(`/products/${args.id}`);
        const product = result.data;
        const prices = product.prices?.map((p) => `${p.price} ${p.currency}`).join(", ") || "N/A";
        return {
          content: [{
            type: "text",
            text: `Product: ${product.name}\nID: ${product.id}\nCode: ${product.code || "N/A"}\nUnit: ${product.unit || "N/A"}\nTax: ${product.tax || 0}%\nPrices: ${prices}\nActive: ${product.active_flag ? "Yes" : "No"}`,
          }],
        };
      }

      case "pipedrive_product_create": {
        const body: Record<string, unknown> = { ...args };
        if (args.prices && typeof args.prices === "string") {
          body.prices = JSON.parse(args.prices as string);
        }
        const result = await client.post<{ success: boolean; data: Product }>("/products", body);
        const product = result.data;
        return {
          content: [{ type: "text", text: `Created product: ${product.name} (ID: ${product.id})` }],
        };
      }

      case "pipedrive_product_update": {
        const { id, prices, ...updateData } = args;
        const body: Record<string, unknown> = { ...updateData };
        if (prices && typeof prices === "string") {
          body.prices = JSON.parse(prices as string);
        }
        const result = await client.put<{ success: boolean; data: Product }>(`/products/${id}`, body);
        const product = result.data;
        return {
          content: [{ type: "text", text: `Updated product: ${product.name} (ID: ${product.id})` }],
        };
      }

      case "pipedrive_product_delete": {
        await client.delete(`/products/${args.id}`);
        return {
          content: [{ type: "text", text: `Deleted product ${args.id}` }],
        };
      }

      case "pipedrive_products_search": {
        const params: Record<string, unknown> = { term: args.term };
        if (args.exact_match !== undefined) params.exact_match = args.exact_match;
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data?: { items?: Array<{ item: Product }> } }>("/products/search", params);
        const items = result.data?.items || [];
        const products = items.map((i) => i.item);
        return {
          content: [{
            type: "text",
            text: `Found ${products.length} products matching "${args.term}"\n${products.map((p) => `- [${p.id}] ${p.name}`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_product_deals": {
        const params: Record<string, unknown> = {};
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: unknown[] }>(`/products/${args.id}/deals`, params);
        const deals = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${deals.length} deals using product ${args.id}` }],
        };
      }

      case "pipedrive_product_files": {
        const params: Record<string, unknown> = {};
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: unknown[] }>(`/products/${args.id}/files`, params);
        const files = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${files.length} files for product ${args.id}` }],
        };
      }

      case "pipedrive_product_followers": {
        const result = await client.get<{ success: boolean; data: Array<{ id: number; user_id: number }> }>(`/products/${args.id}/followers`);
        const followers = result.data || [];
        return {
          content: [{ type: "text", text: `Product ${args.id} has ${followers.length} followers: ${followers.map((f) => f.user_id).join(", ")}` }],
        };
      }

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