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

export const sendMessageToolDefinition: Tool = {
  name: "upwork_send_message",
  description: "Send a message to another user",
  inputSchema: {
    type: "object",
    properties: {
      recipient_id: { type: "string", description: "Recipient user ID" },
      subject: { type: "string", description: "Message subject" },
      body: { type: "string", description: "Message body" },
      thread_id: { type: "string", description: "Thread ID for replies" }
    },
    required: ["recipient_id", "subject", "body"]
  }
};

export async function sendMessageHandler(args: unknown, upworkClient: UpworkClient) {
  const validatedArgs = SendMessageArgsSchema.parse(args);
  
  try {
    const messageData = {
      recipient_id: validatedArgs.recipient_id,
      subject: validatedArgs.subject,
      body: validatedArgs.body,
      thread_id: validatedArgs.thread_id
    };

    const response = await upworkClient.getClient().post('/messages/v3/rooms', messageData);
    
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            message: response.data,
            status: "Message sent successfully"
          }, null, 2)
        }
      ]
    };
  } catch (error) {
    throw upworkClient.handleError(error);
  }
}

export const sendMessageTool = {
  definition: sendMessageToolDefinition,
  handler: sendMessageHandler,
  schema: SendMessageArgsSchema
};