import { Request, Response, NextFunction } from 'express';
import { LocationService } from '../services/LocationService';
import { LocationView } from '../views/LocationView';

export class LocationController {
  constructor(private locationService = new LocationService()) {}

  list = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const locations = await this.locationService.list(req.userId!);
      res.json(LocationView.toList(locations));
    } catch (err) {
      next(err);
    }
  };

  create = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const location = await this.locationService.create(req.userId!, req.body);
      res.status(201).json(LocationView.toHost(location));
    } catch (err) {
      next(err);
    }
  };

  update = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const location = await this.locationService.update(req.userId!, req.params.id, req.body);
      res.json(LocationView.toHost(location));
    } catch (err) {
      next(err);
    }
  };

  delete = async (req: Request, res: Response, next: NextFunction) => {
    try {
      await this.locationService.delete(req.userId!, req.params.id);
      res.status(204).send();
    } catch (err) {
      next(err);
    }
  };
}
