const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const multer = require('multer');
const path = require('path');
const upload = multer(); // Memory storage (for multipart/form-data)

// GET all listings
router.get('/listings', async (req, res) => {
  try {
    const listings = await prisma.listing.findMany({
      include: {
        owner: {
          select: {
            fullnames: true,
            email: true,
            role: true
          }
        },
        listingType: true,
        pricing: true,
        images: true,
        featureListings: {
          include: {
            feature: true
          }
        }
      }
    });

    res.render('listings', { listings });
  } catch (err) {
    console.error(err);
    res.status(500).send('Error fetching listings');
  }
});

// CREATE a new listing
const createListing = async (req, res) => {
  try {
    const {
      name,
      ownerId,
      listingTypeId,
      address,
      neighbourhood,
      latitude,
      longitude,
      noOfBedrooms,
      price
    } = req.body;

    // Ensure features is always an array
    let features = req.body.features || [];
    if (!Array.isArray(features)) features = [features];

    // 1. Create the listing with pricing and features
    const newListing = await prisma.listing.create({
      data: {
        name,
        ownerId: parseInt(ownerId),
        listingTypeId: parseInt(listingTypeId),
        address,
        neighbourhood,
        latitude,
        longitude,
        pricing: {
          create: {
            noOfBedrooms,
            price
          }
        },
        featureListings: {
          create: features.map(featureId => ({
            featureId: parseInt(featureId)
          }))
        }
      },
      include: {
        pricing: true,
        featureListings: true
      }
    });

    // 2. Handle image uploads
    if (req.files && req.files.length > 0) {
      const imageRecords = req.files.map(file => ({
        listingId: newListing.id,
        imagePath: path.join('uploads', file.filename) // Relative path to save
      }));

      await prisma.image.createMany({ data: imageRecords });
    }

    res.json({ success: true, listing: newListing });

  } catch (err) {
    console.error('Error creating listing:', err);
    res.status(500).json({ error: err.message });
  }
};

// DELETE a listing
const deleteListing = async (req, res) => {
  const listingId = parseInt(req.params.id);

  try {
    // 1. Delete related images
    await prisma.image.deleteMany({
      where: { listingId }
    });

    // 2. Delete related pricing
    await prisma.pricing.deleteMany({
      where: { listingId }
    });

    // 3. Delete related feature listings
    await prisma.featureListing.deleteMany({
      where: { listingId }
    });

    // 4. Delete the listing itself
    await prisma.listing.delete({
      where: { id: listingId }
    });

    res.json({ success: true, message: `Listing ${listingId} deleted.` });

  } catch (err) {
    console.error('Error deleting listing:', err);
    res.status(500).json({ error: err.message });
  }
};

module.exports = {
  createListing,
  deleteListing
};
