import type { BigCommerceClient } from '../clients/bigcommerce.js';
import type { Customer, CustomerAddress, CustomerGroup } from '../types/index.js';

export function registerCustomerTools(client: BigCommerceClient) {
  return {
    // Customer CRUD Operations
    bigcommerce_list_customers: {
      description: 'List all customers with optional filters (name, email, customer group, registration date)',
      parameters: {
        type: 'object' as const,
        properties: {
          company: { type: 'string', description: 'Filter by company name' },
          email: { type: 'string', description: 'Filter by email (exact match or partial with :in operator)' },
          first_name: { type: 'string', description: 'Filter by first name' },
          last_name: { type: 'string', description: 'Filter by last name' },
          customer_group_id: { type: 'number', description: 'Filter by customer group ID' },
          min_date_created: { type: 'string', description: 'Minimum registration date (ISO 8601)' },
          max_date_created: { type: 'string', description: 'Maximum registration date (ISO 8601)' },
          min_date_modified: { type: 'string', description: 'Minimum modification date (ISO 8601)' },
          max_date_modified: { type: 'string', description: 'Maximum modification date (ISO 8601)' },
          page: { type: 'number', description: 'Page number (default: 1)' },
          limit: { type: 'number', description: 'Items per page (default: 50, max: 250)' },
        },
      },
      handler: async (params: Record<string, unknown>) => {
        const queryParams: Record<string, string | number> = {};
        if (params.company) queryParams['company:like'] = params.company as string;
        if (params.email) queryParams['email:like'] = params.email as string;
        if (params.first_name) queryParams['first_name:like'] = params.first_name as string;
        if (params.last_name) queryParams['last_name:like'] = params.last_name as string;
        if (params.customer_group_id) queryParams.customer_group_id = params.customer_group_id as number;
        if (params.min_date_created) queryParams['date_created:min'] = params.min_date_created as string;
        if (params.max_date_created) queryParams['date_created:max'] = params.max_date_created as string;
        if (params.min_date_modified) queryParams['date_modified:min'] = params.min_date_modified as string;
        if (params.max_date_modified) queryParams['date_modified:max'] = params.max_date_modified as string;

        const page = (params.page as number) || 1;
        const limit = (params.limit as number) || 50;

        const result = await client.getPage<Customer>('/customers', page, limit, queryParams);
        return { customers: result.data, meta: result.meta };
      },
    },

    bigcommerce_get_customer: {
      description: 'Get a single customer by ID with full details (addresses, attributes)',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          include_addresses: { type: 'boolean', description: 'Include customer addresses (default: true)' },
        },
        required: ['customer_id'],
      },
      handler: async (params: { customer_id: number; include_addresses?: boolean }) => {
        const queryParams = params.include_addresses !== false ? '?include=addresses' : '';
        const result = await client.get<{ data: Customer }>(`/customers/${params.customer_id}${queryParams}`);
        return result.data;
      },
    },

    bigcommerce_create_customer: {
      description: 'Create a new customer',
      parameters: {
        type: 'object' as const,
        properties: {
          first_name: { type: 'string', description: 'First name', required: true },
          last_name: { type: 'string', description: 'Last name', required: true },
          email: { type: 'string', description: 'Email address', required: true },
          phone: { type: 'string', description: 'Phone number' },
          company: { type: 'string', description: 'Company name' },
          customer_group_id: { type: 'number', description: 'Customer group ID' },
          notes: { type: 'string', description: 'Internal notes' },
          tax_exempt_category: { type: 'string', description: 'Tax exemption category' },
          accepts_product_review_abandoned_cart_emails: { type: 'boolean', description: 'Marketing opt-in' },
          authentication: {
            type: 'object',
            description: 'Authentication settings',
            properties: {
              force_password_reset: { type: 'boolean' },
            },
          },
        },
        required: ['first_name', 'last_name', 'email'],
      },
      handler: async (params: Partial<Customer>) => {
        const result = await client.post<{ data: Customer }>('/customers', [params]);
        return result.data;
      },
    },

    bigcommerce_update_customer: {
      description: 'Update an existing customer',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          first_name: { type: 'string', description: 'First name' },
          last_name: { type: 'string', description: 'Last name' },
          email: { type: 'string', description: 'Email address' },
          phone: { type: 'string', description: 'Phone number' },
          company: { type: 'string', description: 'Company name' },
          customer_group_id: { type: 'number', description: 'Customer group ID' },
          notes: { type: 'string', description: 'Internal notes' },
        },
        required: ['customer_id'],
      },
      handler: async (params: { customer_id: number; [key: string]: unknown }) => {
        const { customer_id, ...updateData } = params;
        const result = await client.put<{ data: Customer }>(`/customers/${customer_id}`, [updateData]);
        return result.data;
      },
    },

    bigcommerce_delete_customer: {
      description: 'Delete one or more customers',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_ids: { type: 'array', items: { type: 'number' }, description: 'Array of customer IDs to delete', required: true },
        },
        required: ['customer_ids'],
      },
      handler: async (params: { customer_ids: number[] }) => {
        const ids = params.customer_ids.join(',');
        await client.delete(`/customers?id:in=${ids}`);
        return { success: true, message: `Deleted ${params.customer_ids.length} customers` };
      },
    },

    // Customer Addresses
    bigcommerce_list_customer_addresses: {
      description: 'List all addresses for a customer',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
        },
        required: ['customer_id'],
      },
      handler: async (params: { customer_id: number }) => {
        const result = await client.get<{ data: CustomerAddress[] }>(`/customers/${params.customer_id}/addresses`);
        return result.data;
      },
    },

    bigcommerce_get_customer_address: {
      description: 'Get a specific customer address',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          address_id: { type: 'number', description: 'Address ID', required: true },
        },
        required: ['customer_id', 'address_id'],
      },
      handler: async (params: { customer_id: number; address_id: number }) => {
        const result = await client.get<{ data: CustomerAddress }>(`/customers/${params.customer_id}/addresses/${params.address_id}`);
        return result.data;
      },
    },

    bigcommerce_create_customer_address: {
      description: 'Add a new address to a customer',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          first_name: { type: 'string', description: 'First name', required: true },
          last_name: { type: 'string', description: 'Last name', required: true },
          address1: { type: 'string', description: 'Street address line 1', required: true },
          address2: { type: 'string', description: 'Street address line 2' },
          city: { type: 'string', description: 'City', required: true },
          state_or_province: { type: 'string', description: 'State/province', required: true },
          postal_code: { type: 'string', description: 'Postal code', required: true },
          country_code: { type: 'string', description: '2-letter country code (e.g., US, CA, GB)', required: true },
          phone: { type: 'string', description: 'Phone number' },
          company: { type: 'string', description: 'Company name' },
          address_type: { type: 'string', enum: ['residential', 'commercial'], description: 'Address type' },
        },
        required: ['customer_id', 'first_name', 'last_name', 'address1', 'city', 'state_or_province', 'postal_code', 'country_code'],
      },
      handler: async (params: { customer_id: number; [key: string]: unknown }) => {
        const { customer_id, ...addressData } = params;
        const result = await client.post<{ data: CustomerAddress }>(`/customers/${customer_id}/addresses`, [addressData]);
        return result.data;
      },
    },

    bigcommerce_update_customer_address: {
      description: 'Update a customer address',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          address_id: { type: 'number', description: 'Address ID', required: true },
          first_name: { type: 'string', description: 'First name' },
          last_name: { type: 'string', description: 'Last name' },
          address1: { type: 'string', description: 'Street address line 1' },
          address2: { type: 'string', description: 'Street address line 2' },
          city: { type: 'string', description: 'City' },
          state_or_province: { type: 'string', description: 'State/province' },
          postal_code: { type: 'string', description: 'Postal code' },
          country_code: { type: 'string', description: '2-letter country code' },
          phone: { type: 'string', description: 'Phone number' },
        },
        required: ['customer_id', 'address_id'],
      },
      handler: async (params: { customer_id: number; address_id: number; [key: string]: unknown }) => {
        const { customer_id, address_id, ...updateData } = params;
        const result = await client.put<{ data: CustomerAddress }>(`/customers/${customer_id}/addresses/${address_id}`, [updateData]);
        return result.data;
      },
    },

    bigcommerce_delete_customer_address: {
      description: 'Delete a customer address',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          address_id: { type: 'number', description: 'Address ID', required: true },
        },
        required: ['customer_id', 'address_id'],
      },
      handler: async (params: { customer_id: number; address_id: number }) => {
        await client.delete(`/customers/${params.customer_id}/addresses/${params.address_id}`);
        return { success: true, message: `Address ${params.address_id} deleted` };
      },
    },

    // Customer Groups
    bigcommerce_list_customer_groups: {
      description: 'List all customer groups',
      parameters: {
        type: 'object' as const,
        properties: {
          page: { type: 'number', description: 'Page number (default: 1)' },
          limit: { type: 'number', description: 'Items per page (default: 50)' },
        },
      },
      handler: async (params: { page?: number; limit?: number }) => {
        const page = params.page || 1;
        const limit = params.limit || 50;
        const result = await client.getPage<CustomerGroup>('/customer-groups', page, limit);
        return { groups: result.data, meta: result.meta };
      },
    },

    bigcommerce_get_customer_group: {
      description: 'Get a specific customer group by ID',
      parameters: {
        type: 'object' as const,
        properties: {
          group_id: { type: 'number', description: 'Customer group ID', required: true },
        },
        required: ['group_id'],
      },
      handler: async (params: { group_id: number }) => {
        const result = await client.get<{ data: CustomerGroup }>(`/customer-groups/${params.group_id}`);
        return result.data;
      },
    },

    bigcommerce_create_customer_group: {
      description: 'Create a new customer group',
      parameters: {
        type: 'object' as const,
        properties: {
          name: { type: 'string', description: 'Group name', required: true },
          is_default: { type: 'boolean', description: 'Set as default group' },
          category_access: {
            type: 'object',
            description: 'Category access settings',
            properties: {
              type: { type: 'string', enum: ['all', 'specific', 'none'] },
              categories: { type: 'array', items: { type: 'number' } },
            },
          },
        },
        required: ['name'],
      },
      handler: async (params: Partial<CustomerGroup>) => {
        const result = await client.post<{ data: CustomerGroup }>('/customer-groups', params);
        return result.data;
      },
    },

    bigcommerce_update_customer_group: {
      description: 'Update a customer group',
      parameters: {
        type: 'object' as const,
        properties: {
          group_id: { type: 'number', description: 'Customer group ID', required: true },
          name: { type: 'string', description: 'Group name' },
          is_default: { type: 'boolean', description: 'Set as default group' },
        },
        required: ['group_id'],
      },
      handler: async (params: { group_id: number; [key: string]: unknown }) => {
        const { group_id, ...updateData } = params;
        const result = await client.put<{ data: CustomerGroup }>(`/customer-groups/${group_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_customer_group: {
      description: 'Delete a customer group',
      parameters: {
        type: 'object' as const,
        properties: {
          group_id: { type: 'number', description: 'Customer group ID', required: true },
        },
        required: ['group_id'],
      },
      handler: async (params: { group_id: number }) => {
        await client.delete(`/customer-groups/${params.group_id}`);
        return { success: true, message: `Customer group ${params.group_id} deleted` };
      },
    },

    // Customer Segments (V3 endpoint for advanced segmentation)
    bigcommerce_list_customer_segments: {
      description: 'List all customer segments (advanced filtering/grouping)',
      parameters: {
        type: 'object' as const,
        properties: {
          page: { type: 'number', description: 'Page number (default: 1)' },
          limit: { type: 'number', description: 'Items per page (default: 50)' },
        },
      },
      handler: async (params: { page?: number; limit?: number }) => {
        const page = params.page || 1;
        const limit = params.limit || 50;
        const result = await client.getPage<unknown>('/customers/segments', page, limit);
        return { segments: result.data, meta: result.meta };
      },
    },

    bigcommerce_validate_customer_password: {
      description: 'Validate a customer password (useful for authentication flows)',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID', required: true },
          password: { type: 'string', description: 'Password to validate', required: true },
        },
        required: ['customer_id', 'password'],
      },
      handler: async (params: { customer_id: number; password: string }) => {
        const result = await client.post<{ success: boolean }>(`/customers/${params.customer_id}/validate`, {
          password: params.password,
        });
        return result;
      },
    },
  };
}
