import prisma from '@/lib/prisma';
import { Job, Prisma } from '@prisma/client';

type TransformableJob = Job & {
    skills?: { skill: { name: string } }[];
    applicant_count?: number;
};

export interface JobFilters {
    search?: string;
    location?: string;
    type?: string[];
    salaryMin?: number;
    salaryMax?: number;
    skills?: string[];
    experienceLevel?: string[];
    workLocationType?: string[];
    datePosted?: string; // "24h" | "7d" | "14d" | "30d"
    categoryId?: string;
    industryId?: string;
    companySize?: string[];
    includeUndisclosedSalary?: boolean;
    sort?: string; // "recent" | "salary_high" | "salary_low" | "company_az" | "deadline"
    page?: number;
    pageSize?: number;
}

export interface PaginatedJobs {
    jobs: ReturnType<typeof transformJob>[];
    total: number;
    page: number;
    pageSize: number;
    totalPages: number;
}

function stripHtml(html: string): string {
    if (!html) return '';
    return html.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim().substring(0, 200);
}

function transformJob(job: TransformableJob) {
    return {
        id: job.id,
        title: job.title,
        company: job.company,
        location: job.city
            ? `${job.city}${job.state ? `, ${job.state}` : ''}${job.country ? `, ${job.country}` : ''}`
            : 'Not specified',
        type: job.type,
        salaryMin: job.salary_min ?? undefined,
        salaryMax: job.salary_max ?? undefined,
        currency: job.currency || 'USD',
        hideSalary: job.hide_salary,
        postedAt: job.posted_at.toISOString(),
        description: stripHtml(job.summary || job.description?.substring(0, 300) || ''),
        skills: job.skills?.map((js) => js.skill?.name).filter(Boolean) || [],
        applicants: job.applicant_count || 0,
        featured: job.is_featured || false,
        employerId: job.employer_id,
        status: job.status as 'draft' | 'published' | 'expired' | 'archived',
        expiresAt: job.deadline?.toISOString(),
        experienceLevel: job.experience_level,
        workLocationType: job.work_location_type,
        slug: job.slug,
    };
}

function buildWhereClause(filters?: JobFilters) {
    const where: Prisma.JobWhereInput = {
        status: 'published',
    };

    // Text search across title, company, description
    if (filters?.search) {
        where.OR = [
            { title: { contains: filters.search, mode: 'insensitive' } },
            { company: { contains: filters.search, mode: 'insensitive' } },
            { description: { contains: filters.search, mode: 'insensitive' } },
        ];
    }

    // Location text search
    if (filters?.location) {
        const locationFilter = {
            OR: [
                { city: { contains: filters.location, mode: 'insensitive' as const } },
                { state: { contains: filters.location, mode: 'insensitive' as const } },
                { country: { contains: filters.location, mode: 'insensitive' as const } },
            ],
        };

        if (!where.AND) {
            where.AND = [locationFilter];
        } else if (Array.isArray(where.AND)) {
            where.AND.push(locationFilter);
        } else {
            where.AND = [where.AND, locationFilter];
        }
    }

    // Job type filter (OR within category)
    if (filters?.type && filters.type.length > 0) {
        where.type = { in: filters.type };
    }

    // Work location type filter
    if (filters?.workLocationType && filters.workLocationType.length > 0) {
        where.work_location_type = { in: filters.workLocationType };
    }

    // Experience level filter
    if (filters?.experienceLevel && filters.experienceLevel.length > 0) {
        where.experience_level = { in: filters.experienceLevel };
    }

    // Salary range
    if (filters?.salaryMin) {
        where.salary_max = { gte: filters.salaryMin };
    }
    if (filters?.salaryMax) {
        where.salary_min = { ...(where.salary_min as Prisma.IntFilter || {}), lte: filters.salaryMax };
    }

    // Date posted filter
    if (filters?.datePosted) {
        const now = new Date();
        let cutoff: Date;
        switch (filters.datePosted) {
            case '24h': cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000); break;
            case '7d': cutoff = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); break;
            case '14d': cutoff = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000); break;
            case '30d': cutoff = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000); break;
            default: cutoff = new Date(0);
        }
        if (filters.datePosted !== 'any') {
            where.posted_at = { gte: cutoff };
        }
    }

    // Category/Industry
    if (filters?.categoryId) {
        where.category_id = filters.categoryId;
    }
    if (filters?.industryId) {
        where.industry_id = filters.industryId;
    }

    // Skills filter
    if (filters?.skills && filters.skills.length > 0) {
        where.skills = {
            some: {
                skill: {
                    name: { in: filters.skills, mode: 'insensitive' },
                },
            },
        };
    }

    return where;
}

function buildOrderBy(sort?: string) {
    switch (sort) {
        case 'salary_high':
            return { salary_max: 'desc' as const };
        case 'salary_low':
            return { salary_min: 'asc' as const };
        case 'company_az':
            return { company: 'asc' as const };
        case 'deadline':
            return { deadline: 'asc' as const };
        case 'recent':
        default:
            return { posted_at: 'desc' as const };
    }
}

export class JobService {
    static async getJobs(filters?: JobFilters): Promise<PaginatedJobs> {
        const page = filters?.page || 1;
        const pageSize = filters?.pageSize || 20;
        const skip = (page - 1) * pageSize;
        const where = buildWhereClause(filters);
        const orderBy = buildOrderBy(filters?.sort);

        const [jobs, total] = await Promise.all([
            prisma.job.findMany({
                where,
                include: {
                    skills: { include: { skill: true } },
                },
                orderBy,
                skip,
                take: pageSize,
            }),
            prisma.job.count({ where }),
        ]);

        return {
            jobs: jobs.map(transformJob),
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };
    }

    static async countJobs(): Promise<number> {
        return prisma.job.count({ where: { status: 'published' } });
    }

    static async getJobById(id: string) {
        const job = await prisma.job.findUnique({
            where: { id },
            include: {
                skills: { include: { skill: true } },
                employer: { include: { profile: true } },
            },
        });

        if (!job) return undefined;

        return {
            ...transformJob(job),
            fullDescription: job.description,
            responsibilities: job.responsibilities,
            requiredQualifications: job.required_qualifications,
            benefits: job.benefits,
            summary: job.summary,
            address: job.address,
            salaryType: job.salary_type,
            applicationMethod: job.application_method,
            externalUrl: job.external_url,
            contactEmail: job.contact_email,
            employer: {
                name: job.employer.name,
                companyLogo: job.employer.profile?.company_logo_url ?? undefined,
            },
        };
    }

    static async createJob(data: {
        employer_id: string;
        title: string;
        company: string;
        city?: string;
        type: string;
        salary_min?: number;
        salary_max?: number;
        description?: string;
        skills?: string[];
        status?: string;
        deadline?: Date;
    }) {
        const skillConnections = [];
        if (data.skills) {
            for (const skillName of data.skills) {
                const skill = await prisma.skill.upsert({
                    where: { name: skillName },
                    update: {},
                    create: { name: skillName },
                });
                skillConnections.push({ skill_id: skill.id });
            }
        }

        return prisma.job.create({
            data: {
                employer_id: data.employer_id,
                title: data.title,
                company: data.company,
                city: data.city,
                type: data.type,
                salary_min: data.salary_min,
                salary_max: data.salary_max,
                description: data.description,
                status: data.status || 'draft',
                deadline: data.deadline,
                skills: {
                    create: skillConnections,
                },
            },
        });
    }

    /**
     * Returns counts per filter option for dynamic filter UI.
     * Example: { type: { "full-time": 120, "part-time": 34 }, ... }
     */
    static async getFilterCounts() {
        const baseWhere = { status: 'published' as const };

        const [typeCounts, workLocationCounts, experienceCounts, industryCounts, categoryCounts] = await Promise.all([
            prisma.job.groupBy({
                by: ['type'],
                where: baseWhere,
                _count: { id: true },
            }),
            prisma.job.groupBy({
                by: ['work_location_type'],
                where: baseWhere,
                _count: { id: true },
            }),
            prisma.job.groupBy({
                by: ['experience_level'],
                where: { ...baseWhere, experience_level: { not: null } },
                _count: { id: true },
            }),
            prisma.industry.findMany({
                select: {
                    id: true,
                    name: true,
                    _count: { select: { jobs: { where: baseWhere } } },
                },
                orderBy: { name: 'asc' },
            }),
            prisma.category.findMany({
                select: {
                    id: true,
                    name: true,
                    industry_id: true,
                    _count: { select: { jobs: { where: baseWhere } } },
                },
                orderBy: { name: 'asc' },
            }),
        ]);

        return {
            type: Object.fromEntries(typeCounts.map(t => [t.type, t._count.id])),
            workLocation: Object.fromEntries(workLocationCounts.map(w => [w.work_location_type, w._count.id])),
            experience: Object.fromEntries(experienceCounts.map(e => [e.experience_level!, e._count.id])),
            industries: industryCounts.map(i => ({
                id: i.id,
                name: i.name,
                count: i._count.jobs,
            })),
            categories: categoryCounts.map(c => ({
                id: c.id,
                name: c.name,
                industryId: c.industry_id,
                count: c._count.jobs,
            })),
        };
    }

    /**
     * Returns popular categories with job counts for the Browse page.
     */
    static async getPopularCategories() {
        const baseWhere = { status: 'published' as const };

        const [industries, topCities, featuredEmployers] = await Promise.all([
            prisma.industry.findMany({
                select: {
                    id: true,
                    name: true,
                    _count: { select: { jobs: { where: baseWhere } } },
                    categories: {
                        select: {
                            id: true,
                            name: true,
                            _count: { select: { jobs: { where: baseWhere } } },
                        },
                        orderBy: { name: 'asc' },
                    },
                },
                orderBy: { name: 'asc' },
            }),
            prisma.job.groupBy({
                by: ['city'],
                where: { ...baseWhere, city: { not: null } },
                _count: { id: true },
                orderBy: { _count: { id: 'desc' } },
                take: 10,
            }),
            prisma.user.findMany({
                where: {
                    role: 'employer',
                    is_active: true,
                    jobs: { some: baseWhere },
                },
                select: {
                    id: true,
                    name: true,
                    profile: {
                        select: {
                            company_logo_url: true,
                            company_industry: true,
                        },
                    },
                    _count: { select: { jobs: { where: baseWhere } } },
                },
                orderBy: { jobs: { _count: 'desc' } },
                take: 12,
            }),
        ]);

        return {
            industries: industries.map(i => ({
                id: i.id,
                name: i.name,
                count: i._count.jobs,
                categories: i.categories.map(c => ({
                    id: c.id,
                    name: c.name,
                    count: c._count.jobs,
                })),
            })),
            topCities: topCities.map(c => ({
                city: c.city!,
                count: c._count.id,
            })),
            featuredEmployers: featuredEmployers.map(e => ({
                id: e.id,
                name: e.name,
                logo: e.profile?.company_logo_url ?? null,
                industry: e.profile?.company_industry ?? null,
                openPositions: e._count.jobs,
            })),
        };
    }
}
