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

export const createMilestoneToolDefinition: Tool = {
  name: "upwork_create_milestone",
  description: "Create a milestone for fixed-price contracts",
  inputSchema: {
    type: "object",
    properties: {
      contract_id: { type: "string", description: "Contract ID" },
      description: { type: "string", description: "Milestone description" },
      amount: { type: "number", minimum: 5, description: "Milestone amount" },
      due_date: { type: "string", description: "Due date (YYYY-MM-DD)" }
    },
    required: ["contract_id", "description", "amount"]
  }
};

export async function createMilestoneHandler(args: unknown, upworkClient: UpworkClient) {
  const validatedArgs = CreateMilestoneArgsSchema.parse(args);
  
  try {
    const milestoneData = {
      contract_id: validatedArgs.contract_id,
      description: validatedArgs.description,
      amount: validatedArgs.amount,
      due_date: validatedArgs.due_date
    };

    const response = await upworkClient.getClient().post('/hr/v2/milestones', milestoneData);
    
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            milestone: response.data,
            message: "Milestone created successfully"
          }, null, 2)
        }
      ]
    };
  } catch (error) {
    throw upworkClient.handleError(error);
  }
}

export const createMilestoneTool = {
  definition: createMilestoneToolDefinition,
  handler: createMilestoneHandler,
  schema: CreateMilestoneArgsSchema
};