import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { CommonService } from 'src/common/common.service';
import { ModelsService } from 'src/models/models.service';
import * as dto from './dto';
import { PageType } from './schema/pages.schema';
import { Types } from 'mongoose';

@Injectable()
export class PagesService {
    private readonly logger = new Logger(PagesService.name);
    constructor(
        private readonly models: ModelsService,
        private readonly common: CommonService,
    ) {
        this.createTypes();
    }

    async createTypes() {
        try {
            const array = Object.values(PageType);
            for (const type of array) {
                const exists = await this.models.PageModel.findOne({ page_type: type });
                if (!exists && type != PageType.FAQS) {
                    const newPage = new this.models.PageModel({
                        title: type.replace(/_/g, ' ').toUpperCase(),
                        description: `This is the ${type.replace(/_/g, ' ').toLowerCase()} page.`,
                        page_type: type,
                    });
                    await newPage.save();
                }
            }
        } catch (error) {
            throw error;
        }
    }
    
    async createFaqs(question: string, answere: string): Promise<any> {
        try {
            await this.models.PageModel.create({
                question,
                answere,
                page_type: PageType.FAQS,
                title: null,
                description: null,
                is_deleted: false
            });
            return this.common.successResponse('New FAQ added successfully');
        } catch (error) {
            throw error;
        }
    }

    async getAllpagesData(dto: any): Promise<any> {
        try {
            const { page = 1, limit = 10, search = '' } = dto;
            const options = await this.common.set_options(page, limit);
            const crmData = await this.models.PageModel.find({ page_type: { $ne: PageType.FAQS } }).sort(options.sort).limit(options.limit);
            const total = await this.models.PageModel.countDocuments();
            return this.common.paginatedResponse('Pages found successfully', crmData, total, page, limit);
        } catch (error) {
            throw error;
        }
    }

    async getByPageTypes(type: string): Promise<any> {
        try {
            if (type == PageType.FAQS) {
                const page = await this.models.PageModel.find(
                    { page_type: type },
                    { question: 1, answere: 1, page_type: 1, _id: 1 },
                    { lean: true }
                );
                return this.common.successResponse('Pages found successfully', page);
            }
            const page = await this.models.PageModel.findOne(
                { page_type: type },
                { title: 1, description: 1, page_type: 1, _id: 1 },
                { lean: true }
            );

            return this.common.successResponse('Pages found successfully', page);
        } catch (error) {
            throw error;
        }
    }

    async updatePageTypes(page_id: string, dto: any): Promise<any> {
        try {
            const page = await this.models.PageModel.findOne({ _id: new Types.ObjectId(page_id) });
            if (!page) {
                throw new HttpException(
                    { message: 'Page not found' },
                    HttpStatus.NOT_FOUND
                );
            }

            page.title = dto.title ? dto.title : page.title;
            page.question = dto.question ? dto.question : page.question;
            page.answere = dto.answere ? dto.answere : page.answere;
            page.description = dto.description ? dto.description : page.description;
            await page.save();

            return this.common.successResponse('Page updated successfully', page);
        } catch (error) {
            throw error;
        }
    }

}
