import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ModelService } from '../model/model.service';
import { CommonService } from '../common/common.service';
import * as dto from './dto/index';
import { Types } from 'mongoose';

@Injectable()
export class FaqService {
    constructor(
        private readonly Model: ModelService,
        private readonly CommonService: CommonService
    ) {

    }

    create_faq = async (req, any, body: dto.faq.add_faq) => {
        try {
            const { _id: user_id } = req.user_data; 
        
            const { question, answer } = body;

            const exist = await this.Model.VendorFAQ.findOne(
                { user_id: new Types.ObjectId(user_id), question: question.trim() }
            );
            if(exist) throw new HttpException(`FAQ exist with this question. Please add another one.`, HttpStatus.BAD_REQUEST);

            const faq = await this.Model.VendorFAQ.create({
                user_id: new Types.ObjectId(user_id),
                question: question.trim(),
                answer: answer.trim()
            });
        return faq;
        } catch (error) {
            throw error;
        }
    }

    list_faq = async (req, any, body: dto.faq.get_faqs) => {
        try {
            const { _id: user_id } = req.user_data; 
            const { pagination, limit, search } = body;

            const query: any = {
                is_deleted: false,
                user_id: new Types.ObjectId(user_id)
            };

            const project = { _id: true, question: true, answer: true }
            if (search) query.question = { $regex: search, $options: "i" }; 

            const options = await this.CommonService.set_options(pagination, limit)
            const data = await this.Model.VendorFAQ.find(query, project, options)
            const count = await this.Model.VendorFAQ.countDocuments(query)

            return { count: count, data: data }
        } catch (error) {
            throw error;
        }
    }
}
