const chunks = [];

process.stdin.on('data', chunk => {
  chunks.push(chunk);
});

process.stdin.on('end', () => {
  try {
    const request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
    const values = request.connection && request.connection.values ? request.connection.values : {};

    if (!values.server || !values.database || !values.user || !values.password) {
      process.stdout.write(JSON.stringify({
        success: false,
        error: 'Missing expected buyerDemoDb connection values'
      }));
      process.exit(0);
      return;
    }

    switch (request.operation.name) {
      case 'ListBuyerAccounts': {
        const segment = request.params.segment;
        process.stdout.write(JSON.stringify({
          success: true,
          result: {
            kind: 'rows',
            rowCount: 2,
            rows: [
              {
                Id: 1,
                Company: 'Northwind Retail',
                Email: 'northwind@example.com',
                Segment: segment
              },
              {
                Id: 2,
                Company: 'Contoso Services',
                Email: 'contoso@example.com',
                Segment: segment
              }
            ]
          }
        }));
        return;
      }

      case 'RecordDemoRun':
        process.stdout.write(JSON.stringify({
          success: true,
          result: {
            kind: 'exec',
            affectedRows: 1
          }
        }));
        return;

      default:
        process.stdout.write(JSON.stringify({
          success: false,
          error: `Unknown buyer showcase SQL operation: ${request.operation.name}`
        }));
    }
  } catch (error) {
    process.stdout.write(JSON.stringify({
      success: false,
      error: error instanceof Error ? error.message : String(error)
    }));
  }
});
