import { z } from 'zod'
import type { Tool } from '../../../../types'
import { createIntegrationTool } from '../../../tool'

/**
 * Create a tool that creates a record in Attio CRM
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioCreateRecordTool('attio-prod')
 * const result = await tool.execute({
 *   object: 'people',
 *   values: {
 *     name: 'John Doe',
 *     email_address: 'john@example.com'
 *   }
 * }, context)
 * ```
 */
export function createAttioCreateRecordTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_create_record',
    description: `Create a new record in Attio CRM.

Use this tool to add new records to any Attio object (people, companies, etc.).

Examples:
- Create a person: object="people", values with name and email
- Create a company: object="companies", values with name and domain
- Create a custom object record: specify the object slug

The values parameter should contain field data according to the object's schema.`,
    inputSchema: z.object({
      object: z.string().describe('Object type slug (e.g., "people", "companies")'),
      values: z.record(z.string(), z.unknown()).describe('Record field values as key-value pairs')
    }),
    outputSchema: z.object({
      recordId: z.string().describe('ID of the created record'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'createRecord' as const,
    credentialName
  })
}

/**
 * Create a tool that updates a record in Attio CRM
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioUpdateRecordTool('attio-prod')
 * const result = await tool.execute({
 *   object: 'people',
 *   recordId: 'rec_123',
 *   values: { status: 'active' }
 * }, context)
 * ```
 */
export function createAttioUpdateRecordTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_update_record',
    description: `Update an existing record in Attio CRM.

Use this tool to modify field values on existing records.

Examples:
- Update person status: object="people", recordId, values with status
- Update company information: object="companies", recordId, values with updated fields
- Update custom object: specify object slug and record ID

Only the fields specified in values will be updated. Other fields remain unchanged.`,
    inputSchema: z.object({
      object: z.string().describe('Object type slug (e.g., "people", "companies")'),
      recordId: z.string().describe('ID of the record to update'),
      values: z.record(z.string(), z.unknown()).describe('Field values to update')
    }),
    outputSchema: z.object({
      recordId: z.string().describe('ID of the updated record'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'updateRecord' as const,
    credentialName
  })
}

/**
 * Create a tool that lists records from Attio CRM
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioListRecordsTool('attio-prod')
 * const result = await tool.execute({
 *   object: 'people',
 *   limit: 10
 * }, context)
 * ```
 */
export function createAttioListRecordsTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_list_records',
    description: `List records from Attio CRM with optional filtering.

Use this tool to retrieve multiple records from any Attio object.

Examples:
- List people: object="people"
- List companies: object="companies"
- List with pagination: specify limit and offset
- Filter by attribute: filter={ name: { first_name: { $eq: "John" } } }
- Filter deals by associated person email: filter={ associated_people: { email_addresses: { email_address: { $eq: "john@example.com" } } } }

Filter operators: $eq, $ne, $gt, $gte, $lt, $lte, $contains, $starts_with
Logical operators: $and, $or (wrap array of filters)

Returns an array of records with their field values.`,
    inputSchema: z.object({
      object: z.string().describe('Object type slug (e.g., "people", "companies", "deals")'),
      limit: z.number().optional().describe('Maximum number of records to return (default: 500)'),
      offset: z.number().optional().describe('Number of records to skip for pagination'),
      filter: z.record(z.string(), z.unknown()).optional().describe('Filter criteria - nested object with attribute, field, operator, value'),
      sorts: z.array(z.object({
        attribute: z.string().describe('Attribute slug to sort by'),
        direction: z.enum(['asc', 'desc']).describe('Sort direction'),
        field: z.string().optional().describe('Optional nested field path')
      })).optional().describe('Sort criteria')
    }),
    outputSchema: z.object({
      records: z.array(
        z.object({
          id: z.string().describe('Record ID'),
          values: z.record(z.string(), z.unknown()).describe('Record field values')
        })
      ).describe('Array of records'),
      hasMore: z.boolean().describe('Whether more records are available')
    }),
    integration: 'attio' as const,
    method: 'listRecords' as const,
    credentialName
  })
}

/**
 * Create a tool that gets a single record from Attio CRM
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioGetRecordTool('attio-prod')
 * const result = await tool.execute({
 *   object: 'people',
 *   recordId: 'rec_123'
 * }, context)
 * ```
 */
export function createAttioGetRecordTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_get_record',
    description: `Get a specific record from Attio CRM.

Use this tool to retrieve detailed information about a single record.

Examples:
- Get person details: object="people", recordId
- Get company details: object="companies", recordId
- Get custom object record: specify object slug and record ID

Returns the record with all field values and metadata.`,
    inputSchema: z.object({
      object: z.string().describe('Object type slug (e.g., "people", "companies")'),
      recordId: z.string().describe('ID of the record to retrieve')
    }),
    outputSchema: z.object({
      id: z.string().describe('Record ID'),
      values: z.record(z.string(), z.unknown()).describe('Record field values'),
      createdAt: z.string().describe('ISO timestamp when record was created')
    }),
    integration: 'attio' as const,
    method: 'getRecord' as const,
    credentialName
  })
}

/**
 * Create a tool that deletes a record from Attio CRM
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioDeleteRecordTool('attio-prod')
 * const result = await tool.execute({
 *   object: 'people',
 *   recordId: 'rec_123'
 * }, context)
 * ```
 */
export function createAttioDeleteRecordTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_delete_record',
    description: `Delete a record from Attio CRM.

Use this tool to permanently remove a record from any Attio object.

Examples:
- Delete a person: object="people", recordId
- Delete a company: object="companies", recordId
- Delete a deal: object="deals", recordId
- Delete custom object record: specify object slug and record ID

WARNING: This operation cannot be undone. The record will be permanently deleted.`,
    inputSchema: z.object({
      object: z.string().describe('Object type slug (e.g., "people", "companies")'),
      recordId: z.string().describe('ID of the record to delete')
    }),
    outputSchema: z.object({
      recordId: z.string().describe('ID of the deleted record'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'deleteRecord' as const,
    credentialName
  })
}

/**
 * Create a named version of any Attio tool (for multi-account support)
 *
 * @param toolName - Unique tool name
 * @param credentialName - Name of the Attio credential to use
 * @param method - Attio method to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * // Support multiple Attio accounts
 * const salesTool = createAttioToolNamed('attio_sales_create', 'attio-sales', 'createRecord')
 * const supportTool = createAttioToolNamed('attio_support_create', 'attio-support', 'createRecord')
 * ```
 */
export function createAttioToolNamed(
  toolName: string,
  credentialName: string,
  method: 'createRecord' | 'updateRecord' | 'listRecords' | 'getRecord' | 'deleteRecord'
): Tool {
  const tools = {
    createRecord: () => createAttioCreateRecordTool(credentialName),
    updateRecord: () => createAttioUpdateRecordTool(credentialName),
    listRecords: () => createAttioListRecordsTool(credentialName),
    getRecord: () => createAttioGetRecordTool(credentialName),
    deleteRecord: () => createAttioDeleteRecordTool(credentialName)
  }

  const tool = tools[method]()
  return {
    ...tool,
    name: toolName
  }
}

// ============================================================================
// Schema/Attribute Operations
// ============================================================================

/**
 * Create a tool that lists all objects in an Attio workspace
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioListObjectsTool('attio-prod')
 * const result = await tool.execute({}, context)
 * // Returns: { objects: [{ id, slug, singularNoun, pluralNoun, createdAt }] }
 * ```
 */
export function createAttioListObjectsTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_list_objects',
    description: `List all objects (tables) in the Attio workspace.

Returns both system objects (people, companies, deals) and custom objects.
Use this to discover available object types before querying records or attributes.

Returns for each object: id, slug, singularNoun, pluralNoun, createdAt`,
    inputSchema: z.object({}),
    outputSchema: z.object({
      objects: z.array(z.object({
        id: z.string().describe('Object ID'),
        slug: z.string().describe('API slug (e.g., "people", "companies")'),
        singularNoun: z.string().describe('Display name (singular)'),
        pluralNoun: z.string().describe('Display name (plural)'),
        createdAt: z.string().describe('ISO timestamp')
      })).describe('Array of objects in the workspace')
    }),
    integration: 'attio' as const,
    method: 'listObjects' as const,
    credentialName
  })
}

/**
 * Create a tool that lists attributes for an Attio object
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioListAttributesTool('attio-prod')
 * const result = await tool.execute({ objectSlug: 'people' }, context)
 * // Returns: { attributes: [{ id, slug, title, type, ... }] }
 * ```
 */
export function createAttioListAttributesTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_list_attributes',
    description: `List all attributes (fields) for a specific Attio object.

Returns attribute details including type, title, and constraints.
Use this to discover available fields before creating or updating records.

Attribute types include: text, number, currency, select, checkbox, date, timestamp,
rating, email-address, phone-number, domain, location, record-reference, actor-reference`,
    inputSchema: z.object({
      objectSlug: z.string().describe('Object slug (e.g., "people", "companies", "deals")')
    }),
    outputSchema: z.object({
      attributes: z.array(z.object({
        id: z.string().describe('Attribute ID'),
        slug: z.string().describe('API slug for the attribute'),
        title: z.string().describe('Display name'),
        type: z.string().describe('Attribute type'),
        isSystemAttribute: z.boolean().describe('Whether this is a built-in attribute'),
        isRequired: z.boolean().describe('Whether the attribute is required'),
        isUnique: z.boolean().describe('Whether values must be unique'),
        isMultiselect: z.boolean().describe('Whether multiple values are allowed'),
        isArchived: z.boolean().describe('Whether the attribute is archived')
      })).describe('Array of attributes on the object')
    }),
    integration: 'attio' as const,
    method: 'listAttributes' as const,
    credentialName
  })
}

/**
 * Create a tool that creates a new attribute on an Attio object
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioCreateAttributeTool('attio-prod')
 * const result = await tool.execute({
 *   objectSlug: 'people',
 *   title: 'Lead Source',
 *   apiSlug: 'lead_source',
 *   type: 'select',
 *   config: { options: [{ title: 'Website', isArchived: false }] }
 * }, context)
 * ```
 */
export function createAttioCreateAttributeTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_create_attribute',
    description: `Create a new attribute (field) on an Attio object.

Supported types: text, number, currency, select, checkbox, date, timestamp,
rating, email-address, phone-number, domain, location, record-reference

For select types, provide options in config: { options: [{ title: 'Option 1', isArchived: false }] }

WARNING: This modifies the workspace schema. Cannot be undone - attributes can only be archived, not deleted.`,
    inputSchema: z.object({
      objectSlug: z.string().describe('Object to add attribute to (e.g., "people")'),
      title: z.string().describe('Display name for the attribute'),
      apiSlug: z.string().describe('API slug (snake_case, immutable after creation)'),
      type: z.enum([
        'text', 'number', 'currency', 'select', 'checkbox', 'date', 'timestamp',
        'rating', 'email-address', 'phone-number', 'domain', 'location', 'record-reference'
      ]).describe('Attribute data type'),
      description: z.string().optional().describe('Optional description'),
      isRequired: z.boolean().optional().describe('Whether the attribute is required'),
      isUnique: z.boolean().optional().describe('Whether values must be unique'),
      isMultiselect: z.boolean().optional().describe('Allow multiple values (for select)'),
      config: z.object({
        options: z.array(z.object({
          title: z.string(),
          isArchived: z.boolean()
        })).optional().describe('Options for select type'),
        targetObject: z.string().optional().describe('Target object for record-reference'),
        currencyCode: z.string().optional().describe('Currency code (e.g., "USD")'),
        maxValue: z.number().optional().describe('Max value for rating')
      }).optional().describe('Type-specific configuration')
    }),
    outputSchema: z.object({
      attributeId: z.string().describe('ID of the created attribute'),
      slug: z.string().describe('API slug of the created attribute'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'createAttribute' as const,
    credentialName
  })
}

/**
 * Create a tool that updates an existing attribute on an Attio object
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioUpdateAttributeTool('attio-prod')
 * const result = await tool.execute({
 *   objectSlug: 'people',
 *   attributeSlug: 'lead_source',
 *   title: 'Updated Title',
 *   config: { options: [
 *     { id: 'existing-opt-id', title: 'Website', isArchived: false },
 *     { title: 'New Option', isArchived: false }
 *   ]}
 * }, context)
 * ```
 */
export function createAttioUpdateAttributeTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_update_attribute',
    description: `Update an existing attribute on an Attio object.

Can update: title, description, isRequired, isArchived, config (options)
Cannot update: apiSlug, type (immutable after creation)

IMPORTANT for select options: Include existing option IDs when updating to preserve them.
Options without IDs are treated as new options.

WARNING: This modifies the workspace schema.`,
    inputSchema: z.object({
      objectSlug: z.string().describe('Object containing the attribute'),
      attributeSlug: z.string().describe('Slug of the attribute to update'),
      title: z.string().optional().describe('New display name'),
      description: z.string().optional().describe('New description'),
      isRequired: z.boolean().optional().describe('Whether the attribute is required'),
      isArchived: z.boolean().optional().describe('Archive the attribute (soft delete)'),
      config: z.object({
        options: z.array(z.object({
          id: z.string().optional().describe('Existing option ID (omit for new options)'),
          title: z.string(),
          isArchived: z.boolean()
        })).optional().describe('Options for select type')
      }).optional().describe('Type-specific configuration updates')
    }),
    outputSchema: z.object({
      attributeId: z.string().describe('ID of the updated attribute'),
      slug: z.string().describe('API slug of the updated attribute'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'updateAttribute' as const,
    credentialName
  })
}

// ============================================================================
// Note Operations
// ============================================================================

/**
 * Create a tool that creates a note on an Attio record
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 *
 * @example
 * ```typescript
 * const tool = createAttioCreateNoteTool('attio-prod')
 * const result = await tool.execute({
 *   parentObject: 'people',
 *   parentRecordId: '891dcbfc-9141-415d-9b2a-2238a6cc012d',
 *   title: 'Discovery Call Notes',
 *   format: 'markdown',
 *   content: '## Summary\n\n- Key point 1'
 * }, context)
 * ```
 */
export function createAttioCreateNoteTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_create_note',
    description: `Create a note on an Attio record.

Use this tool to add notes to people, companies, or other Attio records.
Notes support markdown formatting including headings, lists, bold, italic, and links.

Examples:
- Discovery call notes: parentObject="people", title, format="markdown", content with call summary
- Company research notes: parentObject="companies", title, format="plaintext", content
- Follow-up notes: Add additional notes to track ongoing interactions

Each note is independent - you can add multiple notes to the same record over time.`,
    inputSchema: z.object({
      parentObject: z.string().describe('Object type slug (e.g., "people", "companies")'),
      parentRecordId: z.string().describe('ID of the record to attach the note to'),
      title: z.string().describe('Note title (plaintext only, no formatting)'),
      format: z.enum(['plaintext', 'markdown']).describe('Content format: "plaintext" or "markdown"'),
      content: z.string().describe('Note body content'),
      createdAt: z.string().optional().describe('Optional ISO timestamp to override creation time')
    }),
    outputSchema: z.object({
      noteId: z.string().describe('ID of the created note'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'createNote' as const,
    credentialName
  })
}

/**
 * Create a tool that lists notes on an Attio record
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 */
export function createAttioListNotesTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_list_notes',
    description: `List notes attached to an Attio record.

Use this tool to retrieve all notes on a person, company, deal, or other record.

Examples:
- List deal notes: parentObject="deals", parentRecordId
- List person notes: parentObject="people", parentRecordId`,
    inputSchema: z.object({
      parentObject: z.string().describe('Object type slug (e.g., "deals", "people", "companies")'),
      parentRecordId: z.string().describe('ID of the record to list notes for')
    }),
    outputSchema: z.object({
      notes: z.array(z.object({
        noteId: z.string().describe('Note ID'),
        title: z.string().describe('Note title'),
        createdAt: z.string().describe('ISO timestamp of creation')
      })),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'listNotes' as const,
    credentialName
  })
}

/**
 * Create a tool that deletes a note from Attio
 *
 * @param credentialName - Name of the Attio credential to use
 * @returns Tool instance
 */
export function createAttioDeleteNoteTool(credentialName: string): Tool {
  return createIntegrationTool({
    name: 'attio_delete_note',
    description: `Delete a note from Attio by note ID.

Use this tool to remove a specific note. The note ID can be obtained from listNotes.

WARNING: This operation cannot be undone.`,
    inputSchema: z.object({
      noteId: z.string().describe('ID of the note to delete')
    }),
    outputSchema: z.object({
      noteId: z.string().describe('ID of the deleted note'),
      success: z.boolean().describe('Whether the operation succeeded')
    }),
    integration: 'attio' as const,
    method: 'deleteNote' as const,
    credentialName
  })
}
