import {
  McpToolProvider,
  McpToolDefinition,
  McpToolHandler,
  McpContext,
} from '../interfaces';

/**
 * Branch Tools Service
 * Provides MCP tools for branch management and team operations.
 * Used by: ADMIN, SUPERVISOR roles
 */
export class BranchToolsService implements McpToolProvider {
  getTools(): McpToolDefinition[] {
    return [
      {
        name: 'get_branch_info',
        description: 'Obtiene informacion de una sucursal',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: {
              type: 'string',
              format: 'uuid',
              description: 'ID de la sucursal (usa la actual si no se especifica)',
            },
          },
        },
        returns: {
          type: 'object',
          properties: {
            id: { type: 'string' },
            name: { type: 'string' },
            address: { type: 'string' },
            phone: { type: 'string' },
            operating_hours: { type: 'object' },
          },
        },
      },
      {
        name: 'get_branch_report',
        description: 'Genera reporte de desempeno de sucursal',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: { type: 'string', format: 'uuid' },
            period: {
              type: 'string',
              enum: ['today', 'week', 'month'],
              default: 'today',
            },
          },
        },
        returns: { type: 'object' },
      },
      {
        name: 'get_team_performance',
        description: 'Obtiene metricas de desempeno del equipo',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: { type: 'string', format: 'uuid' },
            period: {
              type: 'string',
              enum: ['today', 'week', 'month'],
              default: 'today',
            },
          },
        },
        returns: {
          type: 'object',
          properties: {
            team_size: { type: 'number' },
            members: { type: 'array' },
          },
        },
      },
      {
        name: 'get_employee_schedule',
        description: 'Obtiene horarios de empleados',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: { type: 'string', format: 'uuid' },
            date: { type: 'string', format: 'date' },
            employee_id: { type: 'string', format: 'uuid' },
          },
        },
        returns: { type: 'array', items: { type: 'object' } },
      },
      {
        name: 'get_branch_hours',
        description: 'Obtiene horarios de atencion de la sucursal',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: { type: 'string', format: 'uuid' },
          },
        },
        returns: {
          type: 'object',
          properties: {
            regular: { type: 'object' },
            holidays: { type: 'array' },
          },
        },
      },
      {
        name: 'get_promotions',
        description: 'Obtiene promociones activas',
        category: 'branches',
        parameters: {
          type: 'object',
          properties: {
            branch_id: { type: 'string', format: 'uuid' },
            active_only: { type: 'boolean', default: true },
          },
        },
        returns: { type: 'array', items: { type: 'object' } },
      },
    ];
  }

  getHandler(toolName: string): McpToolHandler | undefined {
    const handlers: Record<string, McpToolHandler> = {
      get_branch_info: this.getBranchInfo.bind(this),
      get_branch_report: this.getBranchReport.bind(this),
      get_team_performance: this.getTeamPerformance.bind(this),
      get_employee_schedule: this.getEmployeeSchedule.bind(this),
      get_branch_hours: this.getBranchHours.bind(this),
      get_promotions: this.getPromotions.bind(this),
    };
    return handlers[toolName];
  }

  private async getBranchInfo(
    params: { branch_id?: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to BranchesService
    const branchId = params.branch_id || context.branchId;
    return {
      id: branchId,
      name: 'Sucursal Centro',
      code: 'SUC-001',
      type: 'store',
      address: {
        street: 'Av. Principal 123',
        city: 'Ciudad de Mexico',
        state: 'CDMX',
        postal_code: '06600',
      },
      phone: '+52 55 1234 5678',
      email: 'centro@erp.com',
      manager: {
        id: 'mgr-001',
        name: 'Juan Perez',
      },
      operating_hours: {
        monday: { open: '09:00', close: '20:00' },
        tuesday: { open: '09:00', close: '20:00' },
        wednesday: { open: '09:00', close: '20:00' },
        thursday: { open: '09:00', close: '20:00' },
        friday: { open: '09:00', close: '20:00' },
        saturday: { open: '10:00', close: '18:00' },
        sunday: { open: 'closed', close: 'closed' },
      },
      message: 'Conectar a BranchesService real',
    };
  }

  private async getBranchReport(
    params: { branch_id?: string; period?: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to ReportsService
    return {
      branch_id: params.branch_id || context.branchId,
      period: params.period || 'today',
      sales: {
        total: 15750.00,
        count: 42,
        avg_ticket: 375.00,
      },
      inventory: {
        value: 250000.00,
        low_stock_items: 5,
        out_of_stock: 2,
      },
      staff: {
        present: 8,
        absent: 1,
        late: 0,
      },
      goals: {
        sales_target: 20000.00,
        progress: 78.75,
      },
      message: 'Conectar a ReportsService real',
    };
  }

  private async getTeamPerformance(
    params: { branch_id?: string; period?: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to HRService + SalesService
    return {
      branch_id: params.branch_id || context.branchId,
      period: params.period || 'today',
      team_size: 8,
      members: [
        { name: 'Ana Garcia', role: 'Vendedor', sales: 4500.00, transactions: 12, avg_ticket: 375.00 },
        { name: 'Carlos Lopez', role: 'Vendedor', sales: 3800.00, transactions: 10, avg_ticket: 380.00 },
        { name: 'Maria Rodriguez', role: 'Cajero', sales: 2500.00, transactions: 8, avg_ticket: 312.50 },
      ],
      top_performer: 'Ana Garcia',
      message: 'Conectar a HRService real',
    };
  }

  private async getEmployeeSchedule(
    _params: { branch_id?: string; date?: string; employee_id?: string },
    _context: McpContext
  ): Promise<any[]> {
    // TODO: Connect to ScheduleService
    return [
      { employee: 'Ana Garcia', shift: 'morning', start: '09:00', end: '15:00', status: 'confirmed' },
      { employee: 'Carlos Lopez', shift: 'afternoon', start: '15:00', end: '21:00', status: 'confirmed' },
      { employee: 'Maria Rodriguez', shift: 'morning', start: '09:00', end: '15:00', status: 'confirmed' },
    ];
  }

  private async getBranchHours(
    _params: { branch_id?: string },
    _context: McpContext
  ): Promise<any> {
    // TODO: Connect to BranchesService
    return {
      regular: {
        monday: { open: '09:00', close: '20:00' },
        tuesday: { open: '09:00', close: '20:00' },
        wednesday: { open: '09:00', close: '20:00' },
        thursday: { open: '09:00', close: '20:00' },
        friday: { open: '09:00', close: '20:00' },
        saturday: { open: '10:00', close: '18:00' },
        sunday: 'Cerrado',
      },
      holidays: [
        { date: '2026-01-01', name: 'Año Nuevo', status: 'closed' },
        { date: '2026-02-03', name: 'Dia de la Constitucion', status: 'closed' },
      ],
      next_closed: '2026-02-03',
      message: 'Conectar a BranchesService real',
    };
  }

  private async getPromotions(
    _params: { branch_id?: string; active_only?: boolean },
    _context: McpContext
  ): Promise<any[]> {
    // TODO: Connect to PromotionsService
    return [
      {
        id: 'promo-001',
        name: '2x1 en productos seleccionados',
        type: 'bogo',
        discount: 50,
        start_date: '2026-01-20',
        end_date: '2026-01-31',
        status: 'active',
        applicable_products: ['category:electronics'],
      },
      {
        id: 'promo-002',
        name: '10% descuento con tarjeta',
        type: 'percentage',
        discount: 10,
        start_date: '2026-01-01',
        end_date: '2026-03-31',
        status: 'active',
        conditions: ['payment_method:card'],
      },
    ];
  }
}
