/**
 * Schedule List Tool
 *
 * List task schedules with optional metadata-based filtering.
 * Supports JSONB containment queries for metadata fields.
 */

import { getToolServices } from '../../registry'
import type { Tool } from '../../types'
import { serviceUnavailable } from '../../types'
import { ListSchedulesInputSchema, ListSchedulesOutputSchema } from './types'
import type { ListSchedulesInput } from './types'

export function createScheduleListTool(): Tool {
  return {
    name: 'schedule_list',
    description: 'List task schedules with optional filters. Supports metadata-based JSONB filtering for finding schedules by contact email or other metadata fields.',
    inputSchema: ListSchedulesInputSchema,
    outputSchema: ListSchedulesOutputSchema,
    async execute({ input, executionContext }) {
      if (!executionContext?.organizationId) {
        throw serviceUnavailable('ExecutionContext', { tool: 'schedule_list', reason: 'organizationId required for multi-tenant isolation' })
      }

      const { taskSchedulerService } = getToolServices()
      if (!taskSchedulerService) {
        throw serviceUnavailable('TaskSchedulerService', {
          message: 'Ensure toolServicesRegistry.initialize() was called in apps/api/src/main.ts',
          tool: 'schedule_list'
        })
      }

      const { targetResourceId, status, metadata, limit } = input as ListSchedulesInput

      const result = await taskSchedulerService.listSchedules({
        organizationId: executionContext.organizationId,
        targetResourceId,
        status,
        metadata,
        limit
      })

      return {
        schedules: result.schedules.map(s => ({
          id: s.id,
          name: s.name,
          status: s.status,
          nextRunAt: s.nextRunAt instanceof Date ? s.nextRunAt.toISOString() : s.nextRunAt ?? null,
          idempotencyKey: s.idempotencyKey ?? null,
          createdAt: s.createdAt instanceof Date ? s.createdAt.toISOString() : s.createdAt
        })),
        total: result.total
      }
    }
  }
}
