import { Sequelize } from 'sequelize';
import Models from '../models';
import { Op } from 'sequelize';
import { PAYMENT, SEA_QA } from '../config/constants';

export class DashboardService {
    private accountId: number;

    constructor(accountId?: number) {
        this.accountId = accountId || 1;
    }

    async getAnalytics(): Promise<any> {
        try {
            // 1. Total Users
            // Get users count for role id 4 only with status 1 (active)
            const totalUsers = await Models.User.count({
                where: { status: 1 },
                include: [{
                    model: Models.UserRole,
                    as: 'userRole',
                    where: { roleId: 4 },
                    required: true
                }]
            });

            // 2. Active Subscription (Monthly, 6 Monthly, Yearly)
            // Check status is in ACTIVE: 1 or CANCELLED: 2, and currentPeriodEnd >= new Date()
            const activeSubscriptions = await Models.Subscription.findAll({
                where: {
                    status: { [Op.in]: [PAYMENT.SUBSCRIPTION_STATUS.ACTIVE, PAYMENT.SUBSCRIPTION_STATUS.CANCELLED] },
                    currentPeriodEnd: { [Op.gte]: new Date() }
                },
                include: [{
                    model: Models.User,
                    as: 'user',
                    required: true,
                    include: [{
                        model: Models.UserSetting,
                        as: 'userSetting',
                        where: { isPremium: true },
                        required: true
                    }]
                }],
                attributes: ['priceId']
            });

            const priceIds = [...new Set(activeSubscriptions.map((s: any) => s.priceId).filter((id: any) => id))];
            const prices = await Models.Price.findAll({
                where: { id: priceIds },
                attributes: ['id', 'duration', 'frequency']
            });

            const priceMap = new Map();
            prices.forEach((p: any) => priceMap.set(p.id, p));

            let monthlySubscriptions = 0;
            let sixMonthlySubscriptions = 0;
            let yearlySubscriptions = 0;

            activeSubscriptions.forEach((sub: any) => {
                const price = priceMap.get(sub.priceId);
                if (price) {
                    if (price.frequency === 'months') {
                        if (price.duration === 1) monthlySubscriptions++;
                        else if (price.duration === 6) sixMonthlySubscriptions++;
                        else if (price.duration === 12) yearlySubscriptions++;
                    } else if (price.frequency === 'years' && price.duration === 1) {
                        yearlySubscriptions++;
                    }
                }
            });

            // 3. Revenue (Total), last 30 days
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
            const revenueResult = await Models.Transaction.sum('amount', {
                where: {
                    status: 1, // Paid
                    paidAt: { [Op.gte]: thirtyDaysAgo }
                }
            });
            const totalRevenueLast30Days = revenueResult || 0;

            // 4. SeaQA (total question, pending question)
            const totalQuestions = await Models.SeaQAQuestion.count();
            const pendingQuestions = await Models.SeaQAQuestion.count({
                where: { status: 'pending' }
            });

            // 5. Answers (total, pending)
            // Exclude draft answers from total count
            const totalAnswers = await Models.SeaQAAnswer.count({
                where: {
                    status: { [Op.ne]: SEA_QA.ANSWER_STATUS.DRAFT }
                }
            });
            const pendingAnswers = await Models.SeaQAAnswer.count({
                where: { status: 'pending_approval' }
            });

            return {
                users: {
                    total: totalUsers
                },
                activeSubscriptions: {
                    monthly: monthlySubscriptions,
                    sixMonthly: sixMonthlySubscriptions,
                    yearly: yearlySubscriptions,
                    total: activeSubscriptions.length
                },
                revenue: {
                    last30Days: totalRevenueLast30Days
                },
                seaQA: {
                    totalQuestions,
                    pendingQuestions,
                    totalAnswers,
                    pendingAnswers
                }
            };
        } catch (error) {
            console.error("Error in DashboardService getAnalytics:", error);
            throw error;
        }
    }
}
