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

export const postJobToolDefinition: Tool = {
  name: "upwork_post_job",
  description: "Post a new job (client feature)",
  inputSchema: {
    type: "object",
    properties: {
      title: { type: "string", description: "Job title" },
      description: { type: "string", description: "Job description" },
      category: { type: "string", description: "Job category" },
      skills: { type: "array", items: { type: "string" }, description: "Required skills" },
      job_type: { type: "string", enum: ["hourly", "fixed"], description: "Job type" },
      budget: { type: "number", description: "Fixed price budget" },
      hourly_rate_min: { type: "number", description: "Minimum hourly rate" },
      hourly_rate_max: { type: "number", description: "Maximum hourly rate" },
      duration: { type: "string", enum: ["1-7 days", "1-4 weeks", "1-3 months", "3-6 months", "6+ months"], description: "Project duration" },
      workload: { type: "string", enum: ["less-than-30", "30-plus"], description: "Hours per week" },
      experience_level: { type: "string", enum: ["entry", "intermediate", "expert"], description: "Required experience level" }
    },
    required: ["title", "description", "category", "skills", "job_type", "duration", "workload", "experience_level"]
  }
};

export async function postJobHandler(args: unknown, upworkClient: UpworkClient) {
  const validatedArgs = PostJobArgsSchema.parse(args);
  
  try {
    const jobData = {
      title: validatedArgs.title,
      description: validatedArgs.description,
      category: validatedArgs.category,
      skills: validatedArgs.skills,
      job_type: validatedArgs.job_type,
      budget: validatedArgs.budget,
      hourly_rate_min: validatedArgs.hourly_rate_min,
      hourly_rate_max: validatedArgs.hourly_rate_max,
      duration: validatedArgs.duration,
      workload: validatedArgs.workload,
      experience_level: validatedArgs.experience_level
    };

    const response = await upworkClient.getClient().post('/profiles/v1/jobs', jobData);
    
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            job: response.data,
            message: "Job posted successfully"
          }, null, 2)
        }
      ]
    };
  } catch (error) {
    throw upworkClient.handleError(error);
  }
}

export const postJobTool = {
  definition: postJobToolDefinition,
  handler: postJobHandler,
  schema: PostJobArgsSchema
};