import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { ListContractsArgsSchema } from "../../schemas/upwork.js";
import { UpworkClient } from "../../services/upwork-client.js";
import { z } from "zod";

export const toolDefinition: Tool = {
  name: "upwork_list_contracts",
  description: "List all contracts (active and completed) with filtering options",
  inputSchema: {
    type: "object",
    properties: {
      status: {
        type: "string",
        enum: ["active", "ended", "cancelled"],
        description: "Filter contracts by status"
      },
      type: {
        type: "string",
        enum: ["hourly", "fixed-price"],
        description: "Filter by contract type"
      },
      page: {
        type: "number",
        minimum: 1,
        description: "Page number for pagination"
      },
      limit: {
        type: "number",
        minimum: 1,
        maximum: 100,
        description: "Maximum number of contracts to return"
      }
    }
  }
};

export const handler = async (args: z.infer<typeof ListContractsArgsSchema>) => {
  try {
    const client = UpworkClient.getInstance();
    
    // Build query parameters
    const params: any = {};
    if (args.status) {
      params.status = args.status;
    }
    if (args.type) {
      params.type = args.type;
    }
    if (args.page) {
      params.page = args.page;
    }
    if (args.limit) {
      params.limit = args.limit;
    }

    const response = await client.get('/hr/v2/userroles', params);
    
    return {
      success: true,
      contracts: response.userroles || [],
      totalContracts: response.userroles?.length || 0,
      pagination: {
        limit: args.limit || 20,
        hasMore: (response.userroles?.length || 0) >= (args.limit || 20)
      }
    };
  } catch (error: any) {
    throw new Error(`Failed to list contracts: ${error.message}`);
  }
};

export { ListContractsArgsSchema as schema } from "../../schemas/upwork.js";