/**
 * Acquisition List Platform Tools
 *
 * Platform tools for managing acquisition lists. Lists work like Google Sheets tabs,
 * organizing contacts into logical groups.
 *
 * Multi-tenancy: All operations are scoped by organizationId from ExecutionContext.
 * Agents cannot specify organizationId - it is always derived from the execution context.
 */

import { z } from 'zod'
import { getToolServices } from '../../registry'
import { serviceUnavailable } from '../../types'
import type { Tool } from '../../types'
import {
  CreateListInputSchema,
  UpdateListInputSchema,
  DeleteListInputSchema,
  ListOutputSchema,
  ListArrayOutputSchema,
  DeleteResultSchema
} from './types'

/**
 * Create a new acquisition list
 *
 * Creates a list for organizing contacts. Lists are organization-scoped
 * and ordered by creation date (newest first) when retrieved.
 */
export function createAcqListCreateTool(): Tool {
  return {
    name: 'acq_list_create',
    description: 'Create a new acquisition list for organizing contacts. Lists work like Google Sheets tabs.',
    inputSchema: CreateListInputSchema,
    outputSchema: ListOutputSchema,
    execute: async ({ input, executionContext }) => {
      const leadService = getToolServices().leadService
      if (!leadService) throw serviceUnavailable('LeadService')
      if (!executionContext?.organizationId) throw serviceUnavailable('ExecutionContext', { reason: 'organizationId required for multi-tenant isolation' })

      const typedInput = input as { name: string; description?: string; buildTemplateId?: string }

      const result = await leadService.createList({
        organizationId: executionContext.organizationId,
        name: typedInput.name,
        description: typedInput.description,
        buildTemplateId: typedInput.buildTemplateId
      })

      return {
        id: result.id,
        organizationId: result.organizationId,
        name: result.name,
        description: result.description,
        createdAt: result.createdAt.toISOString()
      }
    }
  }
}

/**
 * Update an existing acquisition list
 *
 * Updates list metadata (name and/or description). The list must exist
 * and belong to the organization.
 */
export function createAcqListUpdateTool(): Tool {
  return {
    name: 'acq_list_update',
    description: 'Update an existing acquisition list metadata (name or description).',
    inputSchema: UpdateListInputSchema,
    outputSchema: ListOutputSchema,
    execute: async ({ input, executionContext }) => {
      const leadService = getToolServices().leadService
      if (!leadService) throw serviceUnavailable('LeadService')
      if (!executionContext?.organizationId) throw serviceUnavailable('ExecutionContext', { reason: 'organizationId required for multi-tenant isolation' })

      const typedInput = input as { id: string; name?: string; description?: string }

      const result = await leadService.updateList(typedInput.id, {
        name: typedInput.name,
        description: typedInput.description
      })

      return {
        id: result.id,
        organizationId: result.organizationId,
        name: result.name,
        description: result.description,
        createdAt: result.createdAt.toISOString()
      }
    }
  }
}

/**
 * Delete an acquisition list
 *
 * Deletes a list. Contacts in this list will have their list_ids updated
 * to remove this list reference. The list must belong to the organization.
 */
export function createAcqListDeleteTool(): Tool {
  return {
    name: 'acq_list_delete',
    description: 'Delete an acquisition list. Contacts in this list will have their list_ids updated to remove this list.',
    inputSchema: DeleteListInputSchema,
    outputSchema: DeleteResultSchema,
    execute: async ({ input, executionContext }) => {
      const leadService = getToolServices().leadService
      if (!leadService) throw serviceUnavailable('LeadService')
      if (!executionContext?.organizationId) throw serviceUnavailable('ExecutionContext', { reason: 'organizationId required for multi-tenant isolation' })

      const typedInput = input as { id: string }

      await leadService.deleteList(typedInput.id, executionContext.organizationId)
      return { success: true }
    }
  }
}

/**
 * List all acquisition lists for the organization
 *
 * Returns all lists ordered by creation date (newest first).
 * No input parameters required - organization is derived from context.
 */
export function createAcqListListTool(): Tool {
  return {
    name: 'acq_list_list',
    description: 'List all acquisition lists for the organization. Returns lists ordered by creation date (newest first).',
    inputSchema: z.object({}),
    outputSchema: ListArrayOutputSchema,
    execute: async ({ executionContext }) => {
      const leadService = getToolServices().leadService
      if (!leadService) throw serviceUnavailable('LeadService')
      if (!executionContext?.organizationId) throw serviceUnavailable('ExecutionContext', { reason: 'organizationId required for multi-tenant isolation' })

      const results = await leadService.listLists(executionContext.organizationId)

      return results.map(result => ({
        id: result.id,
        organizationId: result.organizationId,
        name: result.name,
        description: result.description,
        createdAt: result.createdAt.toISOString()
      }))
    }
  }
}
