const { Symbol } = require('../models');
const { Op } = require('sequelize');

class SymbolController {
  // Get all symbols with optional filtering
  async getAllSymbols(req, res, next) {
    try {
      const {
        exchange,
        instrumentType,
        isActive,
        limit = 1000,
        offset = 0
      } = req.query;

      const where = {};
      if (exchange) where.exchange = exchange;
      if (instrumentType) where.instrumentType = instrumentType;
      if (isActive !== undefined && isActive !== '') {
        where.isActive = isActive === 'true' || isActive === true;
      }

      const symbols = await Symbol.findAndCountAll({
        where,
        limit: parseInt(limit),
        offset: parseInt(offset),
        order: [['symbol', 'ASC']]
      });

      res.json({
        success: true,
        data: symbols.rows,
        pagination: {
          total: symbols.count,
          limit: parseInt(limit),
          offset: parseInt(offset),
          hasMore: offset + symbols.rows.length < symbols.count
        }
      });
    } catch (error) {
      next(error);
    }
  }

  // Get symbol by ID
  async getSymbolById(req, res, next) {
    try {
      const { id } = req.params;

      const symbol = await Symbol.findByPk(id);

      if (!symbol) {
        const error = new Error('Symbol not found');
        error.statusCode = 404;
        return next(error);
      }

      res.json({
        success: true,
        data: symbol
      });
    } catch (error) {
      next(error);
    }
  }

  // Create new symbol
  async createSymbol(req, res, next) {
    try {
      const symbol = await Symbol.create(req.body);

      res.status(201).json({
        success: true,
        data: symbol,
        message: 'Symbol created successfully'
      });
    } catch (error) {
      next(error);
    }
  }

  // Update symbol
  async updateSymbol(req, res, next) {
    try {
      const { id } = req.params;

      const [updatedRowsCount] = await Symbol.update(req.body, {
        where: { id }
      });

      if (updatedRowsCount === 0) {
        const error = new Error('Symbol not found');
        error.statusCode = 404;
        return next(error);
      }

      const updatedSymbol = await Symbol.findByPk(id);

      res.json({
        success: true,
        data: updatedSymbol,
        message: 'Symbol updated successfully'
      });
    } catch (error) {
      next(error);
    }
  }

  // Delete symbol (soft delete by setting isActive to false)
  async deleteSymbol(req, res, next) {
    try {
      const { id } = req.params;

      const [updatedRowsCount] = await Symbol.update(
        { isActive: false },
        { where: { id } }
      );

      if (updatedRowsCount === 0) {
        const error = new Error('Symbol not found');
        error.statusCode = 404;
        return next(error);
      }

      res.json({
        success: true,
        message: 'Symbol deactivated successfully'
      });
    } catch (error) {
      next(error);
    }
  }

  // Search symbols by symbol name
  async searchSymbols(req, res, next) {
    try {
      const { q, limit = 20 } = req.query;

      if (!q) {
        const error = new Error('Search query is required');
        error.statusCode = 400;
        return next(error);
      }

      const symbols = await Symbol.findAll({
        where: {
          symbol: {
            [Op.iLike]: `%${q}%`
          },
          isActive: true
        },
        limit: parseInt(limit),
        order: [['symbol', 'ASC']]
      });

      res.json({
        success: true,
        data: symbols
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new SymbolController();
