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

export const toolDefinition: Tool = {
  name: "upwork_log_time",
  description: "Log time manually for a contract (for hourly contracts or manual time entry)",
  inputSchema: {
    type: "object",
    properties: {
      contractId: {
        type: "string",
        description: "Contract ID to log time for"
      },
      hours: {
        type: "number",
        minimum: 0.01,
        maximum: 24,
        description: "Number of hours to log (can be decimal)"
      },
      date: {
        type: "string",
        pattern: "^\\d{4}-\\d{2}-\\d{2}$",
        description: "Date to log time for (YYYY-MM-DD format)"
      },
      memo: {
        type: "string",
        maxLength: 500,
        description: "Description of work performed"
      },
      timezone: {
        type: "string",
        description: "Timezone for the logged time (e.g., 'America/New_York')"
      }
    },
    required: ["contractId", "hours", "date", "memo"]
  }
};

export const handler = async (args: z.infer<typeof LogTimeArgsSchema>) => {
  try {
    const client = UpworkClient.getInstance();
    
    const timeData = {
      date: args.date,
      hours: args.hours,
      description: args.description
    };

    const response = await client.post(`/timereports/v1/${args.contract_id}`, timeData);
    
    return {
      success: true,
      loggedTime: {
        contractId: args.contract_id,
        hours: args.hours,
        date: args.date,
        description: args.description,
        status: response.status || 'logged'
      },
      response: response
    };
  } catch (error: any) {
    throw new Error(`Failed to log time: ${error.message}`);
  }
};

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