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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_organizations_list",
    description: "List all organizations with optional filters",
    inputSchema: {
      type: "object",
      properties: {
        filter_id: { type: "number" },
        user_id: { type: "number", description: "Filter by owner" },
        sort: { type: "string" },
        start: { type: "number" },
        limit: { type: "number" },
      },
    },
  },
  {
    name: "pipedrive_organization_get",
    description: "Get a single organization by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_create",
    description: "Create a new organization",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Organization name" },
        owner_id: { type: "number", description: "Owner user ID" },
        address: { type: "string" },
        visible_to: { type: "string", description: "Visibility: 1, 3, 5, 7" },
      },
      required: ["name"],
    },
  },
  {
    name: "pipedrive_organization_update",
    description: "Update an existing organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
        name: { type: "string" },
        owner_id: { type: "number" },
        address: { type: "string" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_delete",
    description: "Delete an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organizations_search",
    description: "Search organizations by term",
    inputSchema: {
      type: "object",
      properties: {
        term: { type: "string", description: "Search term" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["term"],
    },
  },
  {
    name: "pipedrive_organization_merge",
    description: "Merge two organizations",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID to keep" },
        merge_with_id: { type: "number", description: "Organization ID to merge" },
      },
      required: ["id", "merge_with_id"],
    },
  },
  {
    name: "pipedrive_organization_deals",
    description: "List all deals for an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_persons",
    description: "List all persons for an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_activities",
    description: "List all activities for an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_files",
    description: "List all files for an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_organization_followers",
    description: "List all followers for an organization",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Organization ID" },
      },
      required: ["id"],
    },
  },
];

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

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

      case "pipedrive_organization_get": {
        const result = await client.get<{ success: boolean; data: Organization }>(`/organizations/${args.id}`);
        const org = result.data;
        return {
          content: [{
            type: "text",
            text: `Organization: ${org.name}\nID: ${org.id}\nOwner ID: ${org.owner_id || "N/A"}\nAddress: ${org.address || "N/A"}`,
          }],
        };
      }

      case "pipedrive_organization_create": {
        const result = await client.post<{ success: boolean; data: Organization }>("/organizations", args);
        const org = result.data;
        return {
          content: [{ type: "text", text: `Created organization: ${org.name} (ID: ${org.id})` }],
        };
      }

      case "pipedrive_organization_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: Organization }>(`/organizations/${id}`, updateData);
        const org = result.data;
        return {
          content: [{ type: "text", text: `Updated organization: ${org.name} (ID: ${org.id})` }],
        };
      }

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

      case "pipedrive_organizations_search": {
        const params: Record<string, unknown> = { term: args.term };
        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: Organization }> } }>("/organizations/search", params);
        const items = result.data?.items || [];
        const orgs = items.map((i) => i.item);
        return {
          content: [{
            type: "text",
            text: `Found ${orgs.length} organizations matching "${args.term}"\n${orgs.map((o) => `- [${o.id}] ${o.name}`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_organization_merge": {
        await client.put(`/organizations/${args.id}/merge`, { merge_with_id: args.merge_with_id });
        return {
          content: [{ type: "text", text: `Merged organization ${args.merge_with_id} into ${args.id}` }],
        };
      }

      case "pipedrive_organization_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[] }>(`/organizations/${args.id}/deals`, params);
        const deals = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${deals.length} deals for organization ${args.id}` }],
        };
      }

      case "pipedrive_organization_persons": {
        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[] }>(`/organizations/${args.id}/persons`, params);
        const persons = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${persons.length} persons for organization ${args.id}` }],
        };
      }

      case "pipedrive_organization_activities": {
        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[] }>(`/organizations/${args.id}/activities`, params);
        const activities = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${activities.length} activities for organization ${args.id}` }],
        };
      }

      case "pipedrive_organization_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[] }>(`/organizations/${args.id}/files`, params);
        const files = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${files.length} files for organization ${args.id}` }],
        };
      }

      case "pipedrive_organization_followers": {
        const result = await client.get<{ success: boolean; data: Array<{ id: number; user_id: number }> }>(`/organizations/${args.id}/followers`);
        const followers = result.data || [];
        return {
          content: [{ type: "text", text: `Organization ${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);
  }
}
