const mongoose = require('mongoose');

const attachmentSchema = new mongoose.Schema({
    url: {
        type: String,
        required: true
    },
    filename: {
        type: String,
        required: true
    },
    mimetype: {
        type: String
    }
}, { _id: false });

const messageSchema = new mongoose.Schema({
    sender: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        refPath: 'messages.senderModel'
    },
    senderModel: {
        type: String,
        required: true,
        enum: ['User', 'Vendor', 'Driver']
    },
    text: {
        type: String,
        required: true
    },
    attachments: [attachmentSchema],
    isInternal: {
        type: Boolean,
        default: false
    },
    timestamp: {
        type: Date,
        default: Date.now
    }
}, { _id: false });

const ticketSchema = new mongoose.Schema({
    ticketId: {
        type: String,
        unique: true
    },
    // Ticket creator type - determines if it's a user or driver ticket
    creatorType: {
        type: String,
        enum: ['user', 'driver', 'vendor', 'super-admin', 'zone-admin'],
        required: true,
        default: 'user'
    },
    // For user tickets
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    // For driver tickets
    driver: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Driver'
    },
    vendor: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Vendor'
    },
    zone: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Zone'
    },
    // Subject line for user tickets
    subject: {
        type: String
    },
    category: {
        type: String,
        required: true,
        enum: [
            // Common categories
            'Booking Issue',
            'Payment Inquiry',
            'Driver Issue',
            // Driver specific
            'Request Off Time',
            // User specific
            'Refund Request',
            'Safety Concern',
            'Lost Item',
            'Fare Dispute',
            'App Issue',
            'Other'
        ]
    },
    status: {
        type: String,
        default: 'open',
        enum: ['open', 'pending', 'closed']
    },
    priority: {
        type: String,
        default: 'normal',
        enum: ['low', 'normal', 'high', 'urgent']
    },
    escalated: {
        type: Boolean,
        default: false
    },
    escalatedAt: {
        type: Date
    },
    escalatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    assignedTo: {
        type: mongoose.Schema.Types.ObjectId,
        refPath: 'assignedType'
    },
    assignedType: {
        type: String,
        enum: ['User', 'Vendor']
    },
    assignedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    assignedAt: {
        type: Date
    },
    orderId: {
        type: String // String ID like ORD-1245
    },
    booking: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Booking'
    },
    messages: [messageSchema]
}, { timestamps: true });

// Pre-save hook to generate ticketId (TCK-001, etc.)
ticketSchema.pre('save', async function (next) {
    if (!this.ticketId) {
        const lastTicket = await this.constructor.findOne({}, {}, { sort: { 'createdAt': -1 } });
        let nextNumber = 1;
        if (lastTicket && lastTicket.ticketId) {
            const lastNumber = parseInt(lastTicket.ticketId.split('-')[1]);
            if (!isNaN(lastNumber)) {
                nextNumber = lastNumber + 1;
            }
        }
        this.ticketId = `TCK-${nextNumber.toString().padStart(3, '0')}`;
    }
    next();
});

module.exports = mongoose.model('Ticket', ticketSchema);
