import { z } from "zod";
import type { db as prodDb } from "../../../db/index.ts";
import {
	createCategory,
	getAllCategories,
} from "../../services/category.service.ts";

type Db = typeof prodDb;

interface ToolResult {
	content: Array<{ type: "text"; text: string }>;
}

function textResult(data: unknown): ToolResult {
	return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
}

function errorResult(message: string): ToolResult {
	return {
		content: [{ type: "text", text: JSON.stringify({ error: message }) }],
	};
}

export const categoryToolDefinitions = [
	{
		name: "list_categories",
		description: "List all gear categories.",
		inputSchema: {},
	},
	{
		name: "create_category",
		description: "Create a new gear category.",
		inputSchema: {
			name: z.string().describe("Category name"),
			icon: z.string().optional().describe("Icon name (defaults to 'package')"),
		},
	},
];

export function registerCategoryTools(db: Db, userId: number) {
	return {
		list_categories: async (): Promise<ToolResult> => {
			try {
				const cats = await getAllCategories(db, userId);
				return textResult(cats);
			} catch (err) {
				return errorResult((err as Error).message);
			}
		},

		create_category: async (args: {
			name: string;
			icon?: string;
		}): Promise<ToolResult> => {
			try {
				const cat = await createCategory(db, userId, args);
				return textResult(cat);
			} catch (err) {
				return errorResult((err as Error).message);
			}
		},
	};
}
