const { Op } = require('sequelize');
const BaseController = require('./base.controller');
const { Cita, Cliente, Admin, Detallecita, Dermatomafrontal, Dermatomaposterior, Analisis, Resultado } = require('../models');

class CitaController extends BaseController {
  constructor() {
    super(Cita, 'Cita', ['Reason', 'Diagnosis', 'Type']);
  }

  // Sobrescribir getById para incluir relaciones
  getById = async (req, res, next) => {
    try {
      const { id } = req.params;
      const data = await this.model.findByPk(id, {
        include: [
          {
            model: Cliente,
            as: 'cliente',
            attributes: { exclude: ['Password'] }
          },
          {
            model: Admin,
            as: 'admin',
            attributes: { exclude: ['Password'] }
          }
        ]
      });

      if (!data) {
        return res.status(404).json({
          success: false,
          message: `${this.modelName} no encontrado`
        });
      }
      res.json({
        success: true,
        message: `${this.modelName} obtenido exitosamente`,
        data
      });
    } catch (error) {
      next(error);
    }
  };

  // Obtener citas por cliente
  getByCliente = async (req, res, next) => {
    try {
      const { clienteId } = req.params;
      const data = await Cita.findAndCountAll({
        where: { ClienteId: clienteId },
        include: [
          {
            model: Admin,
            as: 'admin',
            attributes: { exclude: ['Password'] }
          }
        ],
        order: [['Appointment', 'DESC']]
      });
      const count = data.length;
      if (count === 0) {
        return res.json(
          {
            success: false,
            message: 'No se encontraron citas para este paciente',
            data: [],
            total: 0
          }
        );
      }

      res.json({
        success: true,
        message: 'Citas obtenidas exitosamente',
        data: data,
        total: count
      });
    } catch (error) {
      next(error);
    }
  };

  // Obtener citas por admin
  getByAdmin = async (req, res, next) => {
    try {
      const { adminId } = req.params;
      const data = await Cita.findAndCountAll({
        where: { AdminId: adminId },
        include: [
          {
            model: Cliente,
            as: 'cliente',
            attributes: { exclude: ['Password'] }
          }
        ],
        order: [['Appointment', 'DESC']]
      });
      const count = data.length;
      if (count === 0) {
        return res.json(
          {
            success: false,
            message: 'No se encontraron agendamientos para este paciente',
            data: [],
            total: 0
          }
        );
      }
      res.json({
        success: true,
        message: 'Citas obtenidas exitosamente',
        data: data,
        total: count
      });
    } catch (error) {
      next(error);
    }
  };

  // Obtener citas por fecha
  getByFecha = async (req, res, next) => {
    try {
      const { fecha } = req.params;
      const startDate = new Date(fecha);
      const endDate = new Date(fecha);
      endDate.setDate(endDate.getDate() + 1);
      const data = await Cita.findAndCountAll({
        where: {
          Appointment: {
            [Op.gte]: startDate,
            [Op.lt]: endDate
          }
        },
        include: [
          {
            model: Cliente,
            as: 'cliente',
            attributes: { exclude: ['Password'] }
          },
          {
            model: Admin,
            as: 'admin',
            attributes: { exclude: ['Password'] }
          }
        ],
        order: [['Appointment', 'ASC']]
      });
      const count = data.length;
      if (count === 0) {
        return res.json(
          {
            success: false,
            message: 'No se encontraron citas para este paciente',
            data: [],
            total: 0
          }
        );
      }
      res.json({
        success: true,
        message: 'Citas obtenidas exitosamente',
        data: data,
        total: count
      });
    } catch (error) {
      next(error);
    }
  };

  // Obtener citas por estado
  getByCondition = async (req, res, next) => {
    try {
      const { condition } = req.params;
      const data = await Cita.findAndCountAll({
        where: { Condition: condition },
        include: [
          {
            model: Cliente,
            as: 'cliente',
            attributes: { exclude: ['Password'] }
          }
        ],
        order: [['Appointment', 'DESC']]
      });
      const count = data.length;
      if (count === 0) {
        return res.json(
          {
            success: false,
            message: 'No se encontraron citas para este paciente',
            data: [],
            total: 0
          }
        );
      }
      res.json({
        success: true,
        message: 'Citas obtenidas exitosamente',
        data: data,
        total: count
      });
    } catch (error) {
      next(error);
    }
  };
}

module.exports = new CitaController();