const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const path = require('path');
const fs = require('fs').promises;

// تحميل بروتوكول gRPC
const PROTO_PATH = path.join(__dirname, '../proto/calculator.proto');
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true
});
const calculatorProto = grpc.loadPackageDefinition(packageDefinition).calculator;

// تخزين العمليات
let operations = [];

class MultiplicationService {
  // دالة الضرب
  multiply(call, callback) {
    const { a, b } = call.request;
    const result = a * b;
    const timestamp = new Date().toISOString();

    const operation = {
      type: 'MULTIPLICATION',
      a,
      b,
      result,
      timestamp
    };

    // حفظ العملية في الذاكرة
    operations.push(operation);

    // حفظ في ملف السجل
    this.logToFile(operation);

    console.log(` Multiplication operation: ${a} × ${b} = ${result}`);

    callback(null, {
      value: result,
      operation: 'MULTIPLICATION'
    });
  }

  // دالة جلب السجل (Streaming)
  getOperationHistory(call) {
    console.log(' Sending operation history...');

    const history = {
      service_name: 'Multiplication Service - Node.js',
      operations: operations
    };

    // إرسال السجل
    call.write(history);
    call.end();
  }

  // دالة حفظ في ملف
  async logToFile(operation) {
    try {
      const logEntry = `[${operation.timestamp}] ${operation.type}: ${operation.a} × ${operation.b} = ${operation.result}\n`;
      await fs.appendFile('operation_log.txt', logEntry);
    } catch (error) {
      console.error(' Failed to write to log file:', error);
    }
  }
}

function main() {
  const server = new grpc.Server();
  const multiplicationService = new MultiplicationService();

  // تسجيل الخدمة
  server.addService(calculatorProto.Calculator.service, {
    Multiply: multiplicationService.multiply.bind(multiplicationService),
    GetOperationHistory: multiplicationService.getOperationHistory.bind(multiplicationService)
  });

  // بدء الخادم
  server.bindAsync(
    '0.0.0.0:50053',
    grpc.ServerCredentials.createInsecure(),
    (error, port) => {
      if (error) {
        console.error(' Failed to start server:', error);
        return;
      }
      console.log(' Multiplication Service (Node.js) running on port 50053');
      console.log(' Ready to receive multiplication requests...');
      console.log(' Powered by Node.js');
    }
  );
}

// معالجة إغلاق التطبيق بشكل أنيق
process.on('SIGINT', () => {
  console.log('\n Shutting down Multiplication Service...');
  process.exit(0);
});

main();