const Area = require("../models/Area");
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");

// Create a new Area
exports.createArea = async (req, res, next) => {
    try {
        const {
            area,
        } = req.body;
  
        Area.create({
            area: area,
        });
  
        res.status(201).json({ success: "Area successfully created!" });
    } catch (err) {
        next(err);
    }
  };

  // Get all Area
exports.getAllArea = async (req, res, next) => {
    try {
      const areas = await Area.findAll();
  
      const areaResponse = areas.map(area = ({

            area,

     }) => ({

            area: area,
           
     })
     
      );
      
      res.status(200).json(areaResponse);
    } catch (error) {
      next(error)
    }
};

// Get Area by Id
exports.getAreaId = async (req, res, next) => {
    const { AreaId } = req.params;
  
    try {
      const areas = await Area.findByPk(AreaId);
  
      if (!areas) {
        return res.status(404).json({ error: 'Area not found' });
      }
  
      res.status(200).json(areas);
    } catch (error) {
        next(error)
    }
  };

  // Delete Area
exports.deleteAreaId = async (req, res) => {
    const { AreaId } = req.params;
  
    try {
      const areas = await Area.findByPk(AreaId);
  
      if (!areas) {
        return res.status(404).json({ error: 'Area not found' });
      }
  
      await areas.destroy();
  
      res.status(201).json({ success: "The Area ID successfully Deleted" });
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  };

  // Update Announcements by ID
exports.updateArea = async (req, res, next) => {
    const { AreaId } = req.params;
    try {
      const areas = await Area.findByPk(AreaId);
  
      if (!areas) {
        return res.status(404).json({ error: 'Area not found' });
      }
  
      const { area } = req.body;
  
      await areas.update({
            area,
            
      });
  
      res.status(200).json(areas);
    } catch (error) {
      next(error)
    }
  };