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

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'
    });
  }

  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();