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

router.post('/', async (req, res) => {
  try {
    await sequelize.query(`
      INSERT INTO bookings (client_id, hall_id, photographer_id, start_time, end_time, total_cost, status)
      VALUES (:clientId, :hallId, :photographerId, :startTime, :endTime, :totalCost, :status)
    `, {
      logging: false,
      type: QueryTypes.INSERT,
      replacements: {
        clientId: req.body.clientId,
        hallId: req.body.hallId,
        photographerId: req.body.photographerId || null,
        startTime: req.body.startTime,
        endTime: req.body.endTime,
        totalCost: req.body.totalCost,
        status: req.body.status || 'pending'
      }
    });
    res.status(201).send('Бронирование успешно создано');
  } catch (error) {
    console.warn('Ошибка при создании бронирования:', error.message);
    res.status(500).send(error.message);
  } finally {
    res.end();
  }
});

router.get('/', async (req, res) => {
  try {
    const bookings = await sequelize.query(`
      SELECT *
      FROM bookings
    `, {
      logging: false,
      type: QueryTypes.SELECT
    });
    res.json(bookings);
  } catch (error) {
    res.status(500).send(error.message);
  }
});

router.patch('/:id(\\d+)', async (req, res) => {
  try {
    await sequelize.query(`
      UPDATE bookings 
      SET 
        status = :status,
        total_cost = :totalCost
      WHERE booking_id = :id
    `, {
      logging: false,
      replacements: {
        id: req.params.id,
        status: req.body.status,
        totalCost: req.body.totalCost
      }
    });
    res.send('Бронирование обновлено');
  } catch (error) {
    res.status(500).send(error.message);
  } finally {
    res.end();
  }
});

router.delete('/:id(\\d+)', async (req, res) => {
  try {
    await sequelize.query(`
      DELETE FROM bookings WHERE booking_id = :id
    `, {
      logging: false,
      replacements: {
        id: req.params.id
      }
    });
    res.status(204).send();
  } catch (error) {
    res.status(500).send(error.message);
  } finally {
    res.end();
  }
});

module.exports = router;