const express = require('express');
const router = express.Router();
const { Schedule } = require('../models');
const { Op } = require('sequelize');

// GET /schedules
// Query: petId (required), year, month (optional, for monthly view)
router.get('/', async (req, res) => {
  try {
    const { petId, year, month } = req.query;

    if (!petId) {
      return res.status(400).json({ message: 'Missing petId query parameter' });
    }

    const whereClause = { petId };

    if (year && month) {
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0, 23, 59, 59); // Last day of month

      whereClause.date = {
        [Op.between]: [startDate, endDate]
      };
    }

    const schedules = await Schedule.findAll({
      where: whereClause,
      order: [['date', 'ASC']],
    });

    res.json(schedules);
  } catch (error) {
    console.error('Error fetching schedules:', error);
    res.status(500).json({ message: 'Server Error', error: error.toString() });
  }
});

// POST /schedules
router.post('/', async (req, res) => {
  try {
    const {
      petId, date, type, isCompleted, title, note,
      repeatInterval, repeatUnit, isAlarmOn, alarmTime
    } = req.body;

    const newSchedule = await Schedule.create({
      petId,
      date: new Date(date),
      type,
      isCompleted: isCompleted || false,
      title,
      note,
      repeatInterval,
      repeatUnit,
      isAlarmOn,
      alarmTime: alarmTime ? new Date(alarmTime) : null,
    });

    res.status(201).json(newSchedule);
  } catch (error) {
    console.error('Error creating schedule:', error);
    res.status(500).json({ message: 'Server Error', error: error.toString() });
  }
});

// PUT /schedules/:id
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    const schedule = await Schedule.findByPk(id);
    if (!schedule) {
      return res.status(404).json({ message: 'Schedule not found' });
    }

    // Safety checks / parsing
    if (updateData.date) updateData.date = new Date(updateData.date);
    if (updateData.alarmTime) updateData.alarmTime = new Date(updateData.alarmTime);

    await schedule.update(updateData);

    res.json(schedule);
  } catch (error) {
    console.error('Error updating schedule:', error);
    res.status(500).json({ message: 'Server Error', error: error.toString() });
  }
});

// DELETE /schedules/:id
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const schedule = await Schedule.findByPk(id);
    if (!schedule) {
      return res.status(404).json({ message: 'Schedule not found' });
    }

    await schedule.destroy();
    res.status(204).send();
  } catch (error) {
    console.error('Error deleting schedule:', error);
    res.status(500).json({ message: 'Server Error', error: error.toString() });
  }
});

module.exports = router;
