const request = require('supertest');
const app = require('../src/app');
const { Candle1h, Symbol, sequelize } = require('../src/models');

describe('Candle Controller Integration Tests', () => {
  let testSymbol;

  beforeAll(async () => {
    // Sync database and cleanup
    await sequelize.sync({ force: true });
    
    // Create fresh test symbol
    testSymbol = await Symbol.create({
      symbol: 'TEST_SYMBOL',
      exchange: 'TEST',
      instrumentType: 'forex'
    });
  });

  afterAll(async () => {
    // Cleanup test data
    await Candle1h.destroy({ where: {} });
    await Symbol.destroy({ where: {} });
    await sequelize.close();
  });

  describe('POST /api/candles/bulk', () => {
    it('should create multiple candles from MT5 payload', async () => {
      const mockCandles = [
        {
          symbolId: testSymbol.id,
          openTime: '2025-10-17 00:00:00',
          closeTime: '2025-10-17 01:00:00',
          open: 1.1000,
          high: 1.1050,
          low: 1.0990,
          close: 1.1025,
          volume: 1000
        },
        {
          symbolId: testSymbol.id,
          openTime: '2025-10-17 01:00:00',
          closeTime: '2025-10-17 02:00:00',
          open: 1.1025,
          high: 1.1075,
          low: 1.1005,
          close: 1.1060,
          volume: 1200
        }
      ];

      const response = await request(app)
        .post('/api/candles/bulk')
        .send({ candles: mockCandles })
        .expect(201);

      expect(response.body.success).toBe(true);
      expect(response.body.message).toBe('2 candles created successfully');
      expect(response.body.data.length).toBe(2);

      // Verify database persistence
      const dbCandles = await Candle1h.findAll({
        where: { symbolId: testSymbol.id },
        order: [['openTime', 'ASC']]
      });

      expect(dbCandles.length).toBe(2);
      expect(Number(dbCandles[0].open)).toBeCloseTo(1.1000);
      expect(Number(dbCandles[1].close)).toBeCloseTo(1.1060);
    });

    it('should reject invalid payload format', async () => {
      const response = await request(app)
        .post('/api/candles/bulk')
        .send({ invalid: 'payload' })
        .expect(400);

      expect(response.body.success).toBe(false);
      expect(response.body.message).toContain('Validation error');
    });

    it('should handle invalid symbol IDs', async () => {
      const invalidCandles = [{
        symbolId: 999,
        openTime: '2025-10-17 00:00:00',
        closeTime: '2025-10-17 01:00:00',
        open: 1.1000,
        high: 1.1050,
        low: 1.0990,
        close: 1.1025,
        volume: 1000
      }];

      const response = await request(app)
        .post('/api/candles/bulk')
        .send({ candles: invalidCandles })
        .expect(400);

      expect(response.body.success).toBe(false);
      expect(response.body.message).toContain('Invalid symbol IDs');
    });
  });
});
