import { z } from 'zod';
import type { CompositeToolDef } from '../../tool-registry.js';
import type { ApiClient } from '../../api-client.js';

async function handler(args: Record<string, unknown>, api: ApiClient): Promise<string> {
  const userId = String(args.userId);

  // Fetch user details and their activity in parallel
  const [user, shifts, canvassDashboard] = await Promise.allSettled([
    api.request('GET', `/api/users/${userId}`),
    api.request('GET', '/api/map/shifts', { limit: 100 }),
    api.request('GET', '/api/map/canvass/admin/dashboard'),
  ]);

  const sections: string[] = [];

  // User details
  if (user.status === 'fulfilled') {
    const u = user.value as any;
    sections.push(
      '## Volunteer Profile\n' +
        `Name: ${u.name || '(not set)'}\n` +
        `Email: ${u.email}\n` +
        `Role: ${u.role}\n` +
        `Registered: ${u.createdAt}\n` +
        `Status: ${u.isBanned ? 'BANNED' : 'Active'}`
    );
  } else {
    sections.push('## Volunteer Profile\n(Failed to fetch user details)');
  }

  // Shift signups for this user
  if (shifts.status === 'fulfilled') {
    const data = shifts.value as any;
    const allShifts = data.shifts || data.data || [];
    const userShifts = allShifts.filter((s: any) =>
      s.signups?.some((su: any) => String(su.userId) === userId)
    );
    sections.push(
      '## Shift Signups\n' +
        `Total signups: ${userShifts.length}\n` +
        JSON.stringify(
          userShifts.map((s: any) => ({
            id: s.id,
            title: s.title,
            startTime: s.startTime,
            endTime: s.endTime,
          })),
          null,
          2
        )
    );
  } else {
    sections.push('## Shift Signups\n(Failed to fetch)');
  }

  // Canvass activity overview
  if (canvassDashboard.status === 'fulfilled') {
    sections.push('## Canvass Dashboard (Platform-wide)\n' + JSON.stringify(canvassDashboard.value, null, 2));
  } else {
    sections.push('## Canvass Activity\n(Failed to fetch)');
  }

  return sections.join('\n\n');
}

export const volunteerSummary: CompositeToolDef = {
  name: 'volunteer_summary',
  description:
    'Get a comprehensive summary of a specific volunteer: profile details, ' +
    'shift signups, canvass activity, and visit history. ' +
    'Provide a user ID to look up their complete volunteer record.',
  inputSchema: {
    userId: z.string().describe('The user ID of the volunteer to summarize'),
  },
  handler,
  tier: 3,
};
