const dotenv = require("dotenv").config();

const S3Helper = require('../helpers/s3Helper');
const destination = require("../models/destinationModel");
const Destination = new destination();
const path = require('path');
const Response = require("../helpers/responseHelper");

const bucket = process.env.AWS_DESTINATION_BUCKET;

class DestinationController {

    async getAllDestinations(req, res) {
        try {
            const results = await Destination.getAll();
            if(results.length === 0){
 return Response.error(
          res,
          "NOT_FOUND",
          "No destinations found",
          404
        );            }
            const destinationsWithUrls = await Promise.all(results.map(async (destination) => {
                const preSignedUrl = await S3Helper.generatePreSignedUrl(bucket,destination.photo);
                return {
                    id: destination.id,
                    name: destination.name,
                    description: destination.description,
                    photo: preSignedUrl,
                };
            }));
      return Response.success(res, destinationsWithUrls);
        } catch (error) {
           return Response.error(
        res,
        "INTERNAL_ERROR",
        "Internal Server Error",
        500
      );
        }
    }

    async getDestinationById(req, res) {
        const { id } = req.params;
        try {
            const destination = await Destination.getById(id);
            if (!destination.length) {
 return Response.error(
          res,
          "NOT_FOUND",
          "Destination not found",
          404
        );            }
            const preSignedUrl = await S3Helper.generatePreSignedUrl(bucket,destination[0].photo);
            const destinationWithUrl = {
                id: destination[0].id,
                name: destination[0].name,
                description: destination[0].description,
                photo: preSignedUrl,
            };
      return Response.success(res, destinationWithUrl);
        } catch (error) {
            console.error(error);
            return Response.error(
        res,
        "INTERNAL_ERROR",
        "Internal Server Error",
        500
      );
        }
    }
  
    async createDestination(req, res) {
        const { name, description } = req.body;
        if(!name || !req.file){
            return Response.error(
              res,
              "VALIDATION_ERROR",
              "Name and photo are mandatory fields",
              400
            );
        }
        try {
            const result = await Destination.create({ name, description, photo: '' });

            const createdId = result[0].insertId;
            const fileExtension = path.extname(req.file.originalname);
            const photoKey = `destination_${createdId}${fileExtension}`;

            const uploadData = await S3Helper.uploadFile(bucket,photoKey, req.file.buffer);
            await Destination.updatePhotoLink(createdId, photoKey);

return Response.success(res, {
        message: "Destination created successfully"
      });        } catch (error) {
            res.send(error);
 return Response.error(
        res,
        "CREATE_FAILED",
        "Internal Server Error",
        500
      );        }
    }
  
    async updateDestination(req, res) {
        const { id } = req.params;
        const { name, description } = req.body;
        if(!name){
 return Response.error(
        res,
        "VALIDATION_ERROR",
        "Name can not be empty",
        400
      );        }
        try {
            const existingDestination = await Destination.getById(id);

            if (!existingDestination.length) {
                return Response.error(
          res,
          "NOT_FOUND",
          "Destination not found",
          404
        );
            }
            if(req.file){
                await S3Helper.deleteFile(bucket,existingDestination.photo);
                const fileExtension = path.extname(req.file.originalname);
                const photoKey = `destination_${createdId}${fileExtension}`;
                await S3Helper.uploadFile(photoKey, req.file.buffer);
                await Destination.updatePhotoLink(createdId, photoKey);
            }
            await Destination.update(id, { name, description});
 return Response.success(res, {
        message: "Destination updated successfully"
      });        } catch (error) {
            console.error(error);
            return Response.error(
        res,
        "UPDATE_FAILED",
        "Internal Server Error",
        500
      );
        }
    }
  
    async deleteDestination(req, res) {
        const { id } = req.params;
        try {
            const destination = await Destination.getById(id);
            if (!destination.length) {
                return Response.error(
          res,
          "NOT_FOUND",
          "Destination not found",
          404
        );
            }

            const photo = destination[0].photo;
            await S3Helper.deleteFile(bucket,photo);
            await Destination.deleteDestination(id);

            return Response.success(res, {
              message: "Destination deleted successfully"
            });
        } catch (error) {
            console.error(error);
            return Response.error(
        res,
        "DELETE_FAILED",
        "Internal Server Error",
        500
      );
        }
    }
}
  
module.exports = DestinationController;