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

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

    get_vendor_list = async (body: dto.admin.get_vendor) => {
        try {
            const { pagination, limit, search } = body;
            const option = await this.CommonService.set_options(pagination, limit);
            
            const project = {
                _id: true,            
                name: true,           
                email: true,
                phone_no: true,           
            };
            
            const query = {
                type: "VENDOR",
                ...(search && { 
                    $or: [
                        { name: { $regex: search, $options: "i" } },
                        { email: { $regex: search, $options: "i" } },
                        { phone_no: { $regex: search, $options: "i" } },
                    ]
                }),
            };

            const data = await this.Model.UserModel.find(query, project, option);
            const count = await this.Model.UserModel.countDocuments(query);

            return { 
                count,
                data
            };
        } catch (err) {
            throw err;
        }
    };

    bulk_notification = async (dto: dto.admin.bulk_notification) => {
        try {
            const { is_send_to_all, vendor_ids, notification_type, title, description } = dto;
    
            const query = is_send_to_all == true ? { type: "VENDOR" } : {
                _id: {
                    $in: vendor_ids
                }
            };

            if(!is_send_to_all && vendor_ids.length <= 0){
                throw new HttpException(
                    `Please select user first!`,
                    HttpStatus.BAD_REQUEST
                )
            }
    
            const users = await this.Model.UserModel.find(query, { email: true, country_code: true, phone_no: true }, { lean: true });

            switch (notification_type.toLowerCase()) {
                case 'email': 
                    const user_emails: string[] = users.map(user => user.email);
                    this.bulk_email_send(user_emails, title, description);
                    break;
                case 'sms': 
                    const phone_numbers: string[] = users.map(user => `${user.email}${user.email}`);
                    this.bulk_sms_send(phone_numbers);
                    break;
                case 'web': 
                    this.bulk_web_notification_send(vendor_ids);
                    break;
                case 'default':
                    default: console.log('Unhandled event:', notification_type);
                break;
            }
            return true
        } catch (error) {
            console.error('Error fetching white label list:', error);
            throw error;
        }
    };

    private async bulk_email_send(emails: string[], title: string, description: string) {
        try {
            console.log('emails', emails, title, description);

            const file_path = path.resolve(__dirname, './assets/email_templates/vendor_notification.html');
            let html = fs.readFileSync(file_path, { encoding: 'utf-8' });
            html = html.replace('%title%', title);
            html = html.replace('%title%', title);
            html = html.replace('%content_desc%', description);

            await this.CommonService.send_bulk_emails(emails, title, html)
        } catch (error) {
            throw error;
        }
    }

    private bulk_sms_send(phone_numbers: string[]) {
        console.log('phone_numbers', phone_numbers)
    }

    private bulk_web_notification_send(vendor_ids: string[]) {
        
    } 

}
