import prisma from '@/lib/prisma';

export interface DashboardStats {
    pendingApprovals: number;
    pendingUrgent: number; // pending > 24h
    activeJobs: number;
    expiringThisWeek: number;
    totalUsers: number;
    newUsersThisWeek: number;
    applicationsToday: number;
    applicationsTrend: number; // % change vs yesterday
}

export interface ActivityEvent {
    id: string;
    type: 'job_posted' | 'job_approved' | 'user_registered' | 'application_submitted';
    description: string;
    entityName: string;
    entityId: string;
    timestamp: string;
    actor?: string;
}

export interface RecentJob {
    id: string;
    title: string;
    company: string;
    postedBy: string;
    postedByEmail: string;
    submittedAt: string;
    status: string;
    isFeatured: boolean;
}

export interface TrendDataPoint {
    date: string;
    label: string;
    posted: number;
    published: number;
}

export interface UserGrowthPoint {
    date: string;
    label: string;
    candidates: number;
    employers: number;
    total: number;
}

export interface SystemHealthItem {
    name: string;
    status: 'healthy' | 'warning' | 'critical';
    label: string;
    detail: string;
    metric?: string;
}

export interface ModerationAnalytics {
    processedToday: number;
    approvedToday: number;
    rejectedToday: number;
    rejectionCategories: { category: string; count: number }[];
    recentActions: any[];
}

export class AdminService {
    /**
     * Get all dashboard stat card numbers
     */
    static async getDashboardStats(): Promise<DashboardStats> {
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000);
        const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        const oneWeekFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

        const [
            pendingApprovals,
            pendingUrgent,
            activeJobs,
            expiringThisWeek,
            totalUsers,
            newUsersThisWeek,
            applicationsToday,
            applicationsYesterday,
        ] = await Promise.all([
            // Pending jobs (status = draft)
            prisma.job.count({ where: { status: 'draft' } }),
            // Pending > 24h
            prisma.job.count({
                where: { status: 'draft', posted_at: { lt: oneDayAgo } },
            }),
            // Active (published)
            prisma.job.count({ where: { status: 'published' } }),
            // Expiring this week
            prisma.job.count({
                where: {
                    status: 'published',
                    deadline: { lte: oneWeekFromNow, gte: now },
                },
            }),
            // Total users
            prisma.user.count(),
            // New users this week
            prisma.user.count({ where: { created_at: { gte: weekAgo } } }),
            // Applications today
            prisma.application.count({ where: { applied_at: { gte: todayStart } } }),
            // Applications yesterday
            prisma.application.count({
                where: {
                    applied_at: { gte: yesterdayStart, lt: todayStart },
                },
            }),
        ]);

        const applicationsTrend =
            applicationsYesterday > 0
                ? Math.round(((applicationsToday - applicationsYesterday) / applicationsYesterday) * 100)
                : applicationsToday > 0
                    ? 100
                    : 0;

        return {
            pendingApprovals,
            pendingUrgent,
            activeJobs,
            expiringThisWeek,
            totalUsers,
            newUsersThisWeek,
            applicationsToday,
            applicationsTrend,
        };
    }

    /**
     * Get recent platform activity for the timeline
     */
    static async getRecentActivity(limit = 15): Promise<ActivityEvent[]> {
        const events: ActivityEvent[] = [];

        // Recent job posts
        const recentJobs = await prisma.job.findMany({
            orderBy: { posted_at: 'desc' },
            take: limit,
            include: { employer: { select: { name: true } } },
        });

        for (const job of recentJobs) {
            events.push({
                id: `job-${job.id}`,
                type: 'job_posted',
                description: `${job.employer.name} posted new job`,
                entityName: job.title,
                entityId: job.id,
                timestamp: job.posted_at.toISOString(),
                actor: job.employer.name,
            });
        }

        // Recent user registrations
        const recentUsers = await prisma.user.findMany({
            orderBy: { created_at: 'desc' },
            take: limit,
            select: { id: true, name: true, role: true, created_at: true },
        });

        for (const user of recentUsers) {
            events.push({
                id: `user-${user.id}`,
                type: 'user_registered',
                description: `New ${user.role} registered`,
                entityName: user.name,
                entityId: user.id,
                timestamp: user.created_at.toISOString(),
            });
        }

        // Recent applications
        const recentApps = await prisma.application.findMany({
            orderBy: { applied_at: 'desc' },
            take: limit,
            include: {
                candidate: { select: { name: true } },
                job: { select: { title: true } },
            },
        });

        for (const app of recentApps) {
            events.push({
                id: `app-${app.id}`,
                type: 'application_submitted',
                description: `${app.candidate.name} applied for`,
                entityName: app.job.title,
                entityId: app.job_id,
                timestamp: app.applied_at.toISOString(),
                actor: app.candidate.name,
            });
        }

        // Sort all events by timestamp descending and return the top N
        events.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
        return events.slice(0, limit);
    }

    /**
     * Get recently submitted jobs for the table
     */
    static async getRecentJobs(limit = 10): Promise<RecentJob[]> {
        const jobs = await prisma.job.findMany({
            orderBy: { posted_at: 'desc' },
            take: limit,
            include: {
                employer: { select: { name: true, email: true } },
            },
        });

        return jobs.map((job) => ({
            id: job.id,
            title: job.title,
            company: job.company,
            postedBy: job.employer.name,
            postedByEmail: job.employer.email,
            submittedAt: job.posted_at.toISOString(),
            status: job.status,
            isFeatured: job.is_featured,
        }));
    }

    /**
     * Get job posting trends for the last N days
     */
    static async getJobTrends(days = 7): Promise<TrendDataPoint[]> {
        const now = new Date();
        const points: TrendDataPoint[] = [];

        for (let i = days - 1; i >= 0; i--) {
            const dayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i);
            const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);

            const [posted, published] = await Promise.all([
                prisma.job.count({
                    where: { posted_at: { gte: dayStart, lt: dayEnd } },
                }),
                prisma.job.count({
                    where: {
                        status: 'published',
                        posted_at: { gte: dayStart, lt: dayEnd },
                    },
                }),
            ]);

            points.push({
                date: dayStart.toISOString().split('T')[0],
                label: dayStart.toLocaleDateString('en-US', { weekday: 'short' }),
                posted,
                published,
            });
        }

        return points;
    }

    /**
     * Get user growth data for the last N days
     */
    static async getUserGrowth(days = 7): Promise<UserGrowthPoint[]> {
        const now = new Date();
        const points: UserGrowthPoint[] = [];

        for (let i = days - 1; i >= 0; i--) {
            const dayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i);
            const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);

            const [candidates, employers] = await Promise.all([
                prisma.user.count({
                    where: {
                        role: 'candidate',
                        created_at: { gte: dayStart, lt: dayEnd },
                    },
                }),
                prisma.user.count({
                    where: {
                        role: 'employer',
                        created_at: { gte: dayStart, lt: dayEnd },
                    },
                }),
            ]);

            points.push({
                date: dayStart.toISOString().split('T')[0],
                label: dayStart.toLocaleDateString('en-US', { weekday: 'short' }),
                candidates,
                employers,
                total: candidates + employers,
            });
        }

        return points;
    }

    /**
     * Get basic system health indicators
     */
    static async getSystemHealth(): Promise<SystemHealthItem[]> {
        const items: SystemHealthItem[] = [];

        // Database health — check if we can query
        try {
            const start = Date.now();
            await prisma.$queryRaw`SELECT 1`;
            const latency = Date.now() - start;

            items.push({
                name: 'Database',
                status: latency < 100 ? 'healthy' : latency < 500 ? 'warning' : 'critical',
                label: latency < 100 ? 'Healthy' : latency < 500 ? 'Slow' : 'Critical',
                detail: `${latency}ms response time`,
                metric: `${latency}ms`,
            });
        } catch {
            items.push({
                name: 'Database',
                status: 'critical',
                label: 'Unreachable',
                detail: 'Cannot connect to database',
            });
        }

        // Job counts as a proxy for data health
        const totalJobs = await prisma.job.count();
        const totalUsers = await prisma.user.count();
        const totalApps = await prisma.application.count();

        items.push({
            name: 'Jobs Data',
            status: 'healthy',
            label: 'Operational',
            detail: `${totalJobs.toLocaleString()} jobs indexed`,
            metric: totalJobs.toLocaleString(),
        });

        items.push({
            name: 'User Accounts',
            status: 'healthy',
            label: 'Operational',
            detail: `${totalUsers.toLocaleString()} registered users`,
            metric: totalUsers.toLocaleString(),
        });

        items.push({
            name: 'Applications',
            status: 'healthy',
            label: 'Operational',
            detail: `${totalApps.toLocaleString()} total applications`,
            metric: totalApps.toLocaleString(),
        });

        return items;
    }

    /**
     * Get advanced moderation analytics
     */
    static async getModerationAnalytics(): Promise<ModerationAnalytics> {
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        const [processedToday, approvedToday, rejectedToday, logs] = await Promise.all([
            prisma.auditLog.count({
                where: {
                    created_at: { gte: todayStart },
                    action: { in: ['job.approved', 'job.rejected', 'job.rejected_advanced', 'job.approve', 'job.reject'] }
                }
            }),
            prisma.auditLog.count({
                where: {
                    created_at: { gte: todayStart },
                    action: { in: ['job.approved', 'job.approve'] }
                }
            }),
            prisma.auditLog.count({
                where: {
                    created_at: { gte: todayStart },
                    action: { in: ['job.rejected', 'job.rejected_advanced', 'job.reject'] }
                }
            }),
            // Fetch recent rejection logs to extract categories
            prisma.auditLog.findMany({
                where: {
                    action: 'job.rejected_advanced',
                    created_at: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } // Last 30 days
                },
                select: { details: true }
            })
        ]);

        // Aggregate categories from rejection logs
        const categoryCounts: Record<string, number> = {};
        logs.forEach(log => {
            const details = log.details as any;
            if (details && details.primaryCategory) {
                categoryCounts[details.primaryCategory] = (categoryCounts[details.primaryCategory] || 0) + 1;
            }
        });

        const rejectionCategories = Object.entries(categoryCounts)
            .map(([category, count]) => ({ category, count }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 5);

        return {
            processedToday,
            approvedToday,
            rejectedToday,
            rejectionCategories,
            recentActions: [] // Could add more if needed
        };
    }
}
