import type { HttpContext } from '@adonisjs/core/http'
import { DateTime } from 'luxon'
import Room from '#models/room'
import Reservation from '#models/reservation'
import {
  createReservationValidator,
  updateReservationValidator,
  createRoomValidator,
  updateRoomValidator,
} from '#validators/reservation'
import logger from '@adonisjs/core/services/logger'

export default class RoomReservationsController {
  /**
   * List all rooms.
   */
  async listRooms() {
    return Room.all()
  }

  /**
   * Create a new room (Admin only).
   */
  async createRoom({ request, response }: HttpContext) {
    try {
      const data = await request.validateUsing(createRoomValidator)
      const room = await Room.create(data)
      return room
    } catch (error) {
      logger.error('Room creation failed: %s', error)
      return response.internalServerError({ message: 'Room creation failed' })
    }
  }

  /**
   * Update a room (Admin only).
   */
  async updateRoom({ request, response }: HttpContext) {
    try {
      const data = await request.validateUsing(updateRoomValidator)
      const room = await Room.find(data.id)
      if (!room) {
        return response.notFound({ message: 'Room not found' })
      }
      room.merge(data)
      await room.save()
      return room
    } catch (error) {
      logger.error('Room update failed: %s', error)
      return response.internalServerError({ message: 'Room update failed' })
    }
  }

  /**
   * Delete a room (Admin only).
   */
  async deleteRoom({ request, response }: HttpContext) {
    const { id } = request.body()
    try {
      const room = await Room.find(id)
      if (!room) {
        return response.notFound({ message: 'Room not found' })
      }
      await room.delete()
      return response.ok({ message: 'Room deleted' })
    } catch (error) {
      logger.error('Room deletion failed: %s', error)
      return response.internalServerError({ message: 'Room deletion failed' })
    }
  }

  /**
   * List all reservations (Frontend/Admin).
   */
  async index() {
    return Reservation.query().preload('room').orderBy('startsAt', 'desc')
  }

  /**
   * Create a new reservation (Admin only).
   */
  async store({ request, response }: HttpContext) {
    try {
      const data = await request.validateUsing(createReservationValidator)
      const reservation = await Reservation.create({
        ...data,
        startsAt: DateTime.fromISO(data.startsAt),
        endsAt: DateTime.fromISO(data.endsAt),
      })
      return reservation
    } catch (error) {
      logger.error('Reservation creation failed: %s', error)
      return response.internalServerError({ message: 'Reservation creation failed' })
    }
  }

  /**
   * Update a reservation (Admin only).
   */
  async update({ request, response }: HttpContext) {
    try {
      const data = await request.validateUsing(updateReservationValidator)
      const reservation = await Reservation.find(data.id)
      if (!reservation) {
        return response.notFound({ message: 'Reservation not found' })
      }
      reservation.merge({
        ...data,
        startsAt: data.startsAt ? DateTime.fromISO(data.startsAt) : undefined,
        endsAt: data.endsAt ? DateTime.fromISO(data.endsAt) : undefined,
      })
      await reservation.save()
      return reservation
    } catch (error) {
      logger.error('Reservation update failed: %s', error)
      return response.internalServerError({ message: 'Reservation update failed' })
    }
  }

  /**
   * Delete a reservation (Admin only).
   */
  async destroy({ request, response }: HttpContext) {
    const { id } = request.body()
    try {
      const reservation = await Reservation.find(id)
      if (!reservation) {
        return response.notFound({ message: 'Reservation not found' })
      }
      await reservation.delete()
      return response.ok({ message: 'Reservation deleted' })
    } catch (error) {
      logger.error('Reservation deletion failed: %s', error)
      return response.internalServerError({ message: 'Reservation deletion failed' })
    }
  }
}
