// controllers/ticketController.js

const Ticket = require('../models/Ticket');
const User   = require('../models/User'); // to populate businessName

// Create a ticket (authenticated users only)
exports.createTicket = async (req, res, next) => {
  try {
    const ticket = await Ticket.create({
      ...req.body,            // title, description, dailyRate, estimatedDays, etc.
      user: req.user._id
    });
    res.status(201).json(ticket);
  } catch (err) {
    next(err);
  }
};

// Get all tickets
// - Admins see every ticket.
// - Regular users see only their own.
exports.getTickets = async (req, res, next) => {
  try {
    const filter = req.user.admin ? {} : { user: req.user._id };
    const tickets = await Ticket.find(filter)
      .populate('user', 'businessName');

    const result = tickets.map(t => {
      const obj = t.toObject();
      return {
        id:            obj._id,
        title:         obj.title,
        description:   obj.description,
        phase:         obj.phase,
        priority:      obj.priority,
        dailyRate:     obj.dailyRate,
        estimatedDays: obj.estimatedDays,
        user:          obj.user._id,
        businessName:  obj.user.businessName
      };
    });

    res.json(result);
  } catch (err) {
    next(err);
  }
};

// Get a single ticket by ID
exports.getTicketById = async (req, res, next) => {
  try {
    const query = req.user.admin
      ? { _id: req.params.id }
      : { _id: req.params.id, user: req.user._id };

    const ticket = await Ticket.findOne(query)
      .populate('user', 'businessName');

    if (!ticket) {
      return res.status(404).json({ message: 'Ticket not found' });
    }

    const obj = ticket.toObject();
    res.json({
      id:            obj._id,
      title:         obj.title,
      description:   obj.description,
      phase:         obj.phase,
      priority:      obj.priority,
      dailyRate:     obj.dailyRate,
      estimatedDays: obj.estimatedDays,
      user:          obj.user._id,
      businessName:  obj.user.businessName
    });
  } catch (err) {
    next(err);
  }
};

// Update a ticket
// - Only the owner or an admin can update.
exports.updateTicket = async (req, res, next) => {
  try {
    const query = req.user.admin
      ? { _id: req.params.id }
      : { _id: req.params.id, user: req.user._id };

    const ticket = await Ticket.findOne(query);
    if (!ticket) {
      return res.status(404).json({ message: 'Ticket not found' });
    }

    // Fields regular users may update:
    const updatableByUser = ['title', 'description', 'priority'];
    updatableByUser.forEach(field => {
      if (req.body[field] !== undefined) {
        ticket[field] = req.body[field];
      }
    });

    // Fields only admins may update:
    if (req.user.admin) {
      if (req.body.phase !== undefined) {
        ticket.phase = req.body.phase;
      }
      if (req.body.dailyRate !== undefined) {
        ticket.dailyRate = req.body.dailyRate;
      }
      if (req.body.estimatedDays !== undefined) {
        ticket.estimatedDays = req.body.estimatedDays;
      }
    }

    const updated = await ticket.save();
    res.json(updated);
  } catch (err) {
    next(err);
  }
};

// Delete a ticket
exports.deleteTicket = async (req, res, next) => {
  try {
    const query = req.user.admin
      ? { _id: req.params.id }
      : { _id: req.params.id, user: req.user._id };

    const ticket = await Ticket.findOne(query);
    if (!ticket) {
      return res.status(404).json({ message: 'Ticket not found' });
    }

    await ticket.remove();
    res.json({ message: 'Ticket removed' });
  } catch (err) {
    next(err);
  }
};