import { z } from 'zod';
import type { AirtableClient } from '../clients/airtable.js';
import { BaseIdSchema, TableIdSchema, FieldIdSchema } from '../types/index.js';

/**
 * Tables Tools
 * 
 * Tools for managing Airtable tables within a base.
 */

export function getTools(client: AirtableClient) {
  return [
    // ========================================================================
    // List Tables
    // ========================================================================
    {
      name: 'airtable_list_tables',
      description:
        'List all tables in a base. Returns table metadata including ID, name, description, primary field, fields schema, and views.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
      }),
      execute: async (args: { baseId: string }) => {
        const response = await client.listTables(args.baseId as any);
        return {
          tables: response.tables.map((t) => ({
            id: t.id,
            name: t.name,
            description: t.description,
            primaryFieldId: t.primaryFieldId,
            fieldCount: t.fields.length,
            viewCount: t.views.length,
          })),
        };
      },
    },

    // ========================================================================
    // Get Table
    // ========================================================================
    {
      name: 'airtable_get_table',
      description:
        'Get full details about a specific table including all field definitions and views. Use this to understand the table schema before creating or updating records.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        tableId: TableIdSchema.describe('The ID of the table (starts with tbl).'),
      }),
      execute: async (args: { baseId: string; tableId: string }) => {
        const table = await client.getTable(args.baseId as any, args.tableId as any);
        return table;
      },
    },

    // ========================================================================
    // Create Table
    // ========================================================================
    {
      name: 'airtable_create_table',
      description:
        'Create a new table in a base. You must specify at least one field. The first field becomes the primary field.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        name: z.string().describe('The name of the new table.'),
        description: z.string().optional().describe('Optional description for the table.'),
        fields: z
          .array(
            z.object({
              name: z.string().describe('Field name.'),
              type: z.string().describe('Field type (e.g., singleLineText, number, multipleSelects).'),
              description: z.string().optional().describe('Optional field description.'),
              options: z.record(z.unknown()).optional().describe('Type-specific options (e.g., choices for select fields).'),
            })
          )
          .min(1)
          .describe('Array of field definitions. First field becomes primary field.'),
      }),
      execute: async (args: {
        baseId: string;
        name: string;
        description?: string;
        fields: Array<{
          name: string;
          type: string;
          description?: string;
          options?: Record<string, unknown>;
        }>;
      }) => {
        // Note: Airtable Meta API for creating tables requires specific endpoint
        // This is a POST to /meta/bases/{baseId}/tables
        const response = await (client as any).metaClient.post(`/bases/${args.baseId}/tables`, {
          name: args.name,
          description: args.description,
          fields: args.fields,
        });
        return response.data;
      },
    },

    // ========================================================================
    // Update Table
    // ========================================================================
    {
      name: 'airtable_update_table',
      description:
        'Update table metadata including name and description. Does not modify fields (use field tools for that).',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        tableId: TableIdSchema.describe('The ID of the table (starts with tbl).'),
        name: z.string().optional().describe('New name for the table.'),
        description: z.string().optional().describe('New description for the table.'),
      }),
      execute: async (args: {
        baseId: string;
        tableId: string;
        name?: string;
        description?: string;
      }) => {
        const updates: Record<string, unknown> = {};
        if (args.name !== undefined) updates.name = args.name;
        if (args.description !== undefined) updates.description = args.description;

        const response = await (client as any).metaClient.patch(
          `/bases/${args.baseId}/tables/${args.tableId}`,
          updates
        );
        return response.data;
      },
    },
  ];
}
