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

export const updateProfileToolDefinition: Tool = {
  name: "upwork_update_profile",
  description: "Update your Upwork profile",
  inputSchema: {
    type: "object",
    properties: {
      title: { type: "string", description: "Professional title" },
      overview: { type: "string", description: "Profile overview/summary" },
      hourly_rate: { type: "number", description: "Hourly rate" },
      skills: { type: "array", items: { type: "string" }, description: "Skills list" },
      location: {
        type: "object",
        properties: {
          country: { type: "string" },
          city: { type: "string" },
          timezone: { type: "string" }
        },
        description: "Location information"
      }
    }
  }
};

export async function updateProfileHandler(args: unknown, upworkClient: UpworkClient) {
  const validatedArgs = UpdateProfileArgsSchema.parse(args);
  
  try {
    const profileData = {
      title: validatedArgs.title,
      overview: validatedArgs.overview,
      hourly_rate: validatedArgs.hourly_rate,
      skills: validatedArgs.skills,
      location: validatedArgs.location
    };

    // Remove undefined fields
    Object.keys(profileData).forEach(key => 
      profileData[key as keyof typeof profileData] === undefined && delete profileData[key as keyof typeof profileData]
    );

    const response = await upworkClient.getClient().put('/profiles/v1/contractors/me', profileData);
    
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            profile: response.data,
            message: "Profile updated successfully"
          }, null, 2)
        }
      ]
    };
  } catch (error) {
    throw upworkClient.handleError(error);
  }
}

export const updateProfileTool = {
  definition: updateProfileToolDefinition,
  handler: updateProfileHandler,
  schema: UpdateProfileArgsSchema
};