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

export const getEarningsToolDefinition: Tool = {
  name: "upwork_get_earnings",
  description: "Get earnings report for a specific period",
  inputSchema: {
    type: "object",
    properties: {
      period: { 
        type: "string", 
        enum: ["this_week", "last_week", "this_month", "last_month", "this_year", "last_year", "custom"], 
        description: "Earnings period" 
      },
      start_date: { type: "string", description: "Start date for custom period (YYYY-MM-DD)" },
      end_date: { type: "string", description: "End date for custom period (YYYY-MM-DD)" }
    },
    required: ["period"]
  }
};

export async function getEarningsHandler(args: unknown, upworkClient: UpworkClient) {
  const validatedArgs = GetEarningsArgsSchema.parse(args);
  
  try {
    const params = new URLSearchParams();
    params.append('period', validatedArgs.period);
    if (validatedArgs.start_date) params.append('start_date', validatedArgs.start_date);
    if (validatedArgs.end_date) params.append('end_date', validatedArgs.end_date);

    const response = await upworkClient.getClient().get(`/gds/finreports/v1/provider/earnings?${params.toString()}`);
    
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            earnings: response.data.earnings || response.data
          }, null, 2)
        }
      ]
    };
  } catch (error) {
    throw upworkClient.handleError(error);
  }
}

export const getEarningsTool = {
  definition: getEarningsToolDefinition,
  handler: getEarningsHandler,
  schema: GetEarningsArgsSchema
};