import type { WrikeClient } from '../clients/wrike.js';
import type { WrikeApproval } from '../types/index.js';

export function createApprovalTools(client: WrikeClient) {
  return {
    // List approvals
    wrike_list_approvals: {
      name: 'wrike_list_approvals',
      description: 'List approvals with optional filters',
      inputSchema: {
        type: 'object',
        properties: {
          taskId: { type: 'string', description: 'Filter by task ID' },
          folderId: { type: 'string', description: 'Filter by folder ID' },
          status: { 
            type: 'string', 
            enum: ['Pending', 'Approved', 'Rejected', 'Cancelled'],
            description: 'Filter by status' 
          },
          updatedDateStart: { type: 'string', description: 'Updated date range begin' },
          updatedDateEnd: { type: 'string', description: 'Updated date range end' },
        },
      },
      handler: async (params: Record<string, unknown>) => {
        let endpoint = '/approvals';
        
        if (params.taskId) {
          endpoint = `/tasks/${params.taskId}/approvals`;
        } else if (params.folderId) {
          endpoint = `/folders/${params.folderId}/approvals`;
        }
        
        const queryParams: Record<string, unknown> = {};
        if (params.status) queryParams.status = params.status;
        
        if (params.updatedDateStart || params.updatedDateEnd) {
          queryParams.updatedDate = {
            start: params.updatedDateStart,
            end: params.updatedDateEnd,
          };
        }
        
        const response = await client.get<WrikeApproval>(endpoint, queryParams);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    // Get approval by ID
    wrike_get_approval: {
      name: 'wrike_get_approval',
      description: 'Get a specific approval by ID',
      inputSchema: {
        type: 'object',
        properties: {
          approvalId: { type: 'string', description: 'Approval ID (required)' },
        },
        required: ['approvalId'],
      },
      handler: async (params: { approvalId: string }) => {
        const response = await client.get<WrikeApproval>(`/approvals/${params.approvalId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // Create approval
    wrike_create_approval: {
      name: 'wrike_create_approval',
      description: 'Create a new approval',
      inputSchema: {
        type: 'object',
        properties: {
          title: { type: 'string', description: 'Approval title (required)' },
          description: { type: 'string', description: 'Approval description' },
          approvers: { type: 'array', items: { type: 'string' }, description: 'Approver user IDs (required)' },
          dueDate: { type: 'string', description: 'Due date (YYYY-MM-DD)' },
          taskIds: { type: 'array', items: { type: 'string' }, description: 'Related task IDs' },
          folderIds: { type: 'array', items: { type: 'string' }, description: 'Related folder IDs' },
        },
        required: ['title', 'approvers'],
      },
      handler: async (params: { title: string; approvers: string[]; [key: string]: unknown }) => {
        const body: Record<string, unknown> = {
          title: params.title,
          approverIds: params.approvers,
        };
        
        if (params.description) body.description = params.description;
        if (params.dueDate) body.dueDate = params.dueDate;
        if (params.taskIds) body.taskIds = params.taskIds;
        if (params.folderIds) body.folderIds = params.folderIds;
        
        const response = await client.post<WrikeApproval>('/approvals', body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // Update approval
    wrike_update_approval: {
      name: 'wrike_update_approval',
      description: 'Update an existing approval',
      inputSchema: {
        type: 'object',
        properties: {
          approvalId: { type: 'string', description: 'Approval ID (required)' },
          title: { type: 'string', description: 'New approval title' },
          description: { type: 'string', description: 'New approval description' },
          status: { 
            type: 'string', 
            enum: ['Pending', 'Approved', 'Rejected', 'Cancelled'],
            description: 'New status' 
          },
        },
        required: ['approvalId'],
      },
      handler: async (params: { approvalId: string; [key: string]: unknown }) => {
        const body: Record<string, unknown> = {};
        
        if (params.title) body.title = params.title;
        if (params.description !== undefined) body.description = params.description;
        if (params.status) body.status = params.status;
        
        const response = await client.put<WrikeApproval>(`/approvals/${params.approvalId}`, body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // Delete approval
    wrike_delete_approval: {
      name: 'wrike_delete_approval',
      description: 'Delete an approval',
      inputSchema: {
        type: 'object',
        properties: {
          approvalId: { type: 'string', description: 'Approval ID (required)' },
        },
        required: ['approvalId'],
      },
      handler: async (params: { approvalId: string }) => {
        const response = await client.delete<WrikeApproval>(`/approvals/${params.approvalId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // Submit approval decision
    wrike_submit_approval_decision: {
      name: 'wrike_submit_approval_decision',
      description: 'Submit an approval decision (approve/reject)',
      inputSchema: {
        type: 'object',
        properties: {
          approvalId: { type: 'string', description: 'Approval ID (required)' },
          decision: { 
            type: 'string', 
            enum: ['Approved', 'Rejected'],
            description: 'Decision (required)' 
          },
          comment: { type: 'string', description: 'Decision comment' },
        },
        required: ['approvalId', 'decision'],
      },
      handler: async (params: { approvalId: string; decision: string; comment?: string }) => {
        const body: Record<string, unknown> = {
          decision: params.decision,
        };
        
        if (params.comment) body.comment = params.comment;
        
        const response = await client.post(`/approvals/${params.approvalId}/decisions`, body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },
  };
}
