File size: 6,019 Bytes
959b027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca368c8
 
 
 
 
959b027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1029f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959b027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca368c8
 
 
959b027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca368c8
 
 
 
959b027
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { supabase } from '../../db/supabase';
import { createLogger } from '../../utils/logger';

const logger = createLogger('MessageManager');

interface BotMessage {
  id: string;
  bot_id: string;
  key: string;
  ar_value: string;
  en_value: string;
  description?: string;
  created_at: string;
  updated_at: string;
}

class MessageManager {
  private static instance: MessageManager;
  private messages: Map<string, BotMessage> = new Map();
  private language: 'ar' | 'en' = 'ar';

  private constructor() {}

  static getInstance(): MessageManager {
    if (!MessageManager.instance) {
      MessageManager.instance = new MessageManager();
    }
    return MessageManager.instance;
  }

  setLanguage(lang: 'ar' | 'en') {
    this.language = lang;
    logger.info(`Language set to: ${lang}`);
  }

  getLanguage(): 'ar' | 'en' {
    return this.language;
  }

  async loadMessages() {
    try {
      const { data, error } = await supabase
        .from('bot_messages')
        .select('*')

      if (error) throw error;

      this.messages.clear();
      data.forEach((message: BotMessage) => {
        this.messages.set(message.key, message);
      });

      // Add default messages if not in database
      this.addDefaultMessages();

      logger.info(`Messages loaded successfully for bot `);
    } catch (error) {
      logger.error('Error loading messages:', error);
      throw error;
    }
  }

  private addDefaultMessages() {
    const defaultMessages = {
      'balance_update_notification': {
        ar_value: '💰 <b>تحديث الرصيد</b>\n\n' +
                 'تم تحديث رصيدك:\n' +
                 'الرصيد السابق: {old_balance}$\n' +
                 'الرصيد الجديد: {new_balance}$\n' +
                 'نوع التغيير: {change_type}\n' +
                 'قيمة التغيير: {change_amount}$',
        en_value: '💰 <b>Balance Update</b>\n\n' +
                 'Your balance has been updated:\n' +
                 'Previous balance: ${old_balance}\n' +
                 'New balance: ${new_balance}\n' +
                 'Change type: {change_type}\n' +
                 'Change amount: ${change_amount}'
      },
      'search_product_prompt': {
        ar_value: 'الرجاء إدخال اسم الخدمة التي تبحث عنها:',
        en_value: 'Please enter the name of the service you are looking for:'
      },
      'no_search_results': {
        ar_value: 'عذراً، لم يتم العثور على نتائج لبحثك.',
        en_value: 'Sorry, no results found for your search.'
      },
      'invalid_search_input': {
        ar_value: 'الرجاء إدخال ما لا يقل عن حرفين للبحث.',
        en_value: 'Please enter at least 2 characters to search.'
      },
      'search_country_prompt': {
        ar_value: 'الرجاء إدخال اسم الدولة أو رمزها أو علمها:',
        en_value: 'Please enter the country name, code, or flag:'
      },
      'no_country_search_results': {
        ar_value: 'عذراً، لم يتم العثور على دول مطابقة لبحثك.',
        en_value: 'Sorry, no matching countries found for your search.'
      },
      'affordable_products_list': {
        ar_value: 'المنتجات التي يمكنك شراؤها برصيدك الحالي ({balance}):',
        en_value: 'Products you can buy with your current balance ({balance}):'
      },
      'no_affordable_products': {
        ar_value: 'عذراً، لا توجد منتجات يمكنك شراؤها برصيدك الحالي ({balance}).',
        en_value: 'Sorry, no products can be bought with your current balance ({balance}).'
      },
      'error_user_not_found': {
        ar_value: '❌ لم يتم العثور على معلومات المستخدم.',
        en_value: '❌ User information not found.'
      },
      'error_invalid_page': {
        ar_value: '❌ رقم الصفحة غير صحيح.',
        en_value: '❌ Invalid page number.'
      },
      'error_invalid_filter': {
        ar_value: '❌ نوع الفلتر غير صحيح.',
        en_value: '❌ Invalid filter type.'
      },
      'error_user_state_not_found': {
        ar_value: '❌ لم يتم العثور على حالة المستخدم.',
        en_value: '❌ User state not found.'
      },
      'error_general': {
        ar_value: '❌ حدث خطأ. يرجى المحاولة مرة أخرى.',
        en_value: '❌ An error occurred. Please try again.'
      }
    };

    Object.entries(defaultMessages).forEach(([key, value]) => {
      if (!this.messages.has(key)) {
        this.messages.set(key, {
          id: key,
          bot_id: 'default',
          key,
          ar_value: value.ar_value,
          en_value: value.en_value,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        });
      }
    });
  }

  getMessage(key: string): string {
    const message = this.messages.get(key);
    if (!message) {
      logger.warn(`Message not found for key: ${key}`);
      return `${key}`;
    }
    const value = this.language === 'ar' ? message.ar_value : message.en_value;
    logger.debug(`Retrieved message for key '${key}': ${value.substring(0, 100)}...`);
    return value;
  }

  async updateMessage(key: string, arValue: string, enValue: string, description?: string) {
    try {
      const { data, error } = await supabase
        .from('bot_messages')
        .upsert({
          key,
          ar_value: arValue,
          en_value: enValue,
          description
        })
        .select()
        .single();

      if (error) throw error;

      if (data) {
        this.messages.set(key, data);
      }

      return data;
    } catch (error) {
      logger.error('Error updating message:', error);
      throw error;
    }
  }

  async reloadMessages() {
    await this.loadMessages();
  }
}

export const messageManager = MessageManager.getInstance();