import { Request, Response, NextFunction } from 'express';
import { BookingService } from '../services/BookingService';
import { BookingView } from '../views/BookingView';

export class BookingController {
  constructor(private bookingService = new BookingService()) {}

  list = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { status, from, to, page, limit } = req.query as {
        status?: 'pending' | 'confirmed' | 'cancelled' | 'failed';
        from?: string;
        to?: string;
        page?: string;
        limit?: string;
      };
      const { bookings, pagination } = await this.bookingService.listForHost(req.userId!, {
        status,
        from,
        to,
        page: page ? parseInt(page, 10) : 1,
        limit: limit ? parseInt(limit, 10) : 20,
      });
      res.json(BookingView.toList(bookings, pagination));
    } catch (err) {
      next(err);
    }
  };

  cancel = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const booking = await this.bookingService.cancelByHost(
        req.userId!,
        req.params.id,
        req.body.reason,
      );
      res.json(BookingView.toHostList(booking));
    } catch (err) {
      next(err);
    }
  };

  reschedule = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const booking = await this.bookingService.reschedule(
        req.userId!,
        req.params.id,
        req.body.startTime,
      );
      res.json(BookingView.toHostList(booking));
    } catch (err) {
      next(err);
    }
  };

  updateOutcome = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const booking = await this.bookingService.updateMeetingOutcome(
        req.userId!,
        req.params.id,
        req.body,
      );
      res.json(BookingView.toHostList(booking));
    } catch (err) {
      next(err);
    }
  };
}
