import type { WrikeClient } from '../clients/wrike.js';
import type { 
  WrikeWorkSchedule, 
  WrikeDataExport, 
  WrikeAuditLogEntry, 
  WrikeBlueprint,
  WrikeAccount,
  WrikeInvitation 
} from '../types/index.js';

export function createMiscTools(client: WrikeClient) {
  return {
    // ===== WORK SCHEDULES =====
    wrike_list_work_schedules: {
      name: 'wrike_list_work_schedules',
      description: 'List all work schedules',
      inputSchema: {
        type: 'object',
        properties: {},
      },
      handler: async () => {
        const response = await client.get<WrikeWorkSchedule>('/workschedules');
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    wrike_get_work_schedule: {
      name: 'wrike_get_work_schedule',
      description: 'Get a specific work schedule by ID',
      inputSchema: {
        type: 'object',
        properties: {
          scheduleId: { type: 'string', description: 'Work schedule ID (required)' },
        },
        required: ['scheduleId'],
      },
      handler: async (params: { scheduleId: string }) => {
        const response = await client.get<WrikeWorkSchedule>(`/workschedules/${params.scheduleId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // ===== DATA EXPORT =====
    wrike_start_data_export: {
      name: 'wrike_start_data_export',
      description: 'Start a data export job',
      inputSchema: {
        type: 'object',
        properties: {
          resources: { 
            type: 'array', 
            items: { type: 'string' },
            description: 'Resources to export (Tasks, Folders, etc.)' 
          },
        },
      },
      handler: async (params: { resources?: string[] }) => {
        const body: Record<string, unknown> = {};
        if (params.resources) body.resources = params.resources;
        
        const response = await client.post<WrikeDataExport>('/data_export', body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    wrike_get_data_export_status: {
      name: 'wrike_get_data_export_status',
      description: 'Get status of a data export job',
      inputSchema: {
        type: 'object',
        properties: {
          exportId: { type: 'string', description: 'Export ID (required)' },
        },
        required: ['exportId'],
      },
      handler: async (params: { exportId: string }) => {
        const response = await client.get<WrikeDataExport>(`/data_export/${params.exportId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // ===== AUDIT LOG =====
    wrike_get_audit_log: {
      name: 'wrike_get_audit_log',
      description: 'Get audit log entries',
      inputSchema: {
        type: 'object',
        properties: {
          eventDateStart: { type: 'string', description: 'Event date range begin (ISO 8601)' },
          eventDateEnd: { type: 'string', description: 'Event date range end (ISO 8601)' },
          operations: { type: 'array', items: { type: 'string' }, description: 'Filter by operations' },
          userIds: { type: 'array', items: { type: 'string' }, description: 'Filter by user IDs' },
          limit: { type: 'number', description: 'Maximum entries to return' },
        },
      },
      handler: async (params: Record<string, unknown>) => {
        const queryParams: Record<string, unknown> = {};
        
        if (params.operations) queryParams.operations = params.operations;
        if (params.userIds) queryParams.userIds = params.userIds;
        if (params.limit) queryParams.limit = params.limit;
        
        if (params.eventDateStart || params.eventDateEnd) {
          queryParams.eventDate = {
            start: params.eventDateStart,
            end: params.eventDateEnd,
          };
        }
        
        const response = await client.get<WrikeAuditLogEntry>('/audit_log', queryParams);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    // ===== BLUEPRINTS / TEMPLATES =====
    wrike_list_blueprints: {
      name: 'wrike_list_blueprints',
      description: 'List all blueprints/templates',
      inputSchema: {
        type: 'object',
        properties: {},
      },
      handler: async () => {
        const response = await client.get<WrikeBlueprint>('/blueprints');
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    wrike_get_blueprint: {
      name: 'wrike_get_blueprint',
      description: 'Get a specific blueprint by ID',
      inputSchema: {
        type: 'object',
        properties: {
          blueprintId: { type: 'string', description: 'Blueprint ID (required)' },
        },
        required: ['blueprintId'],
      },
      handler: async (params: { blueprintId: string }) => {
        const response = await client.get<WrikeBlueprint>(`/blueprints/${params.blueprintId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    wrike_launch_blueprint: {
      name: 'wrike_launch_blueprint',
      description: 'Launch a blueprint to create a project from template',
      inputSchema: {
        type: 'object',
        properties: {
          blueprintId: { type: 'string', description: 'Blueprint ID (required)' },
          parent: { type: 'string', description: 'Parent folder ID (required)' },
          title: { type: 'string', description: 'New project title' },
        },
        required: ['blueprintId', 'parent'],
      },
      handler: async (params: { blueprintId: string; parent: string; title?: string }) => {
        const body: Record<string, unknown> = {
          parent: params.parent,
        };
        
        if (params.title) body.title = params.title;
        
        const response = await client.post(`/blueprints/${params.blueprintId}/launch`, body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    // ===== ACCOUNT & VERSION =====
    wrike_get_account: {
      name: 'wrike_get_account',
      description: 'Get account information',
      inputSchema: {
        type: 'object',
        properties: {
          fields: { type: 'array', items: { type: 'string' }, description: 'Additional fields' },
        },
      },
      handler: async (params: { fields?: string[] }) => {
        const response = await client.get<WrikeAccount>('/account', {
          fields: params.fields,
        });
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    wrike_get_version: {
      name: 'wrike_get_version',
      description: 'Get Wrike API version',
      inputSchema: {
        type: 'object',
        properties: {},
      },
      handler: async () => {
        const response = await client.get('/version');
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    // ===== INVITATIONS =====
    wrike_list_invitations: {
      name: 'wrike_list_invitations',
      description: 'List all pending invitations',
      inputSchema: {
        type: 'object',
        properties: {},
      },
      handler: async () => {
        const response = await client.get<WrikeInvitation>('/invitations');
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    wrike_invite_user: {
      name: 'wrike_invite_user',
      description: 'Invite a user to the account',
      inputSchema: {
        type: 'object',
        properties: {
          email: { type: 'string', description: 'User email (required)' },
          firstName: { type: 'string', description: 'First name' },
          lastName: { type: 'string', description: 'Last name' },
          role: { type: 'string', description: 'User role' },
          external: { type: 'boolean', description: 'External user' },
        },
        required: ['email'],
      },
      handler: async (params: { email: string; [key: string]: unknown }) => {
        const body: Record<string, unknown> = {
          email: params.email,
        };
        
        if (params.firstName) body.firstName = params.firstName;
        if (params.lastName) body.lastName = params.lastName;
        if (params.role) body.role = params.role;
        if (params.external !== undefined) body.external = params.external;
        
        const response = await client.post<WrikeInvitation>('/invitations', body);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    wrike_delete_invitation: {
      name: 'wrike_delete_invitation',
      description: 'Cancel/delete an invitation',
      inputSchema: {
        type: 'object',
        properties: {
          invitationId: { type: 'string', description: 'Invitation ID (required)' },
        },
        required: ['invitationId'],
      },
      handler: async (params: { invitationId: string }) => {
        const response = await client.delete<WrikeInvitation>(`/invitations/${params.invitationId}`);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data[0], null, 2),
            },
          ],
        };
      },
    },

    // ===== COLORS =====
    wrike_list_colors: {
      name: 'wrike_list_colors',
      description: 'List all available colors for folders and tasks',
      inputSchema: {
        type: 'object',
        properties: {},
      },
      handler: async () => {
        const response = await client.get('/colors');
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },

    // ===== IDS HELPER =====
    wrike_query_ids: {
      name: 'wrike_query_ids',
      description: 'Convert permalinks to IDs or vice versa',
      inputSchema: {
        type: 'object',
        properties: {
          ids: { type: 'array', items: { type: 'string' }, description: 'IDs to query' },
          permalinks: { type: 'array', items: { type: 'string' }, description: 'Permalinks to query' },
        },
      },
      handler: async (params: { ids?: string[]; permalinks?: string[] }) => {
        const queryParams: Record<string, unknown> = {};
        
        if (params.ids) queryParams.ids = params.ids;
        if (params.permalinks) queryParams.permalinks = params.permalinks;
        
        const response = await client.get('/ids', queryParams);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response.data, null, 2),
            },
          ],
        };
      },
    },
  };
}
