/**
 * Compatibility layer — wraps Prisma calls with the old db.read() interface.
 * This allows existing pages/components to work without rewriting them.
 * 
 * TODO: Gradually migrate all files to use Prisma directly, then remove this file.
 */
import prisma from '@/lib/prisma';

// === Type exports for backward compatibility ===

export interface User {
    id: string;
    email: string;
    password?: string;
    passwordHash?: string;
    role: 'candidate' | 'employer' | 'admin';
    name: string;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
    bio?: string;
    aboutMe?: string;
    skills: string[];
    title?: string;
    company?: string;
    location?: string;
    phone?: string;
    resumeUrl?: string;
    coverLetter?: string;
    portfolioUrl?: string;
    linkedIn?: string;
    github?: string;
    website?: string;
    companyWebsite?: string;
    companySize?: string;
    companyIndustry?: string;
    companyLogo?: string;
    companyDescription?: string;
    description?: string; // alias for bio or companyDescription
    savedJobIds: string[];
    experience: WorkExperience[];
    education: EducationEntry[];
    createdAt?: string;
}

export interface WorkExperience {
    id: string;
    title: string;
    company: string;
    location?: string;
    startDate: string;
    endDate?: string;
    current?: boolean;
    description?: string;
}

export interface EducationEntry {
    id: string;
    institution: string;
    degree: string;
    field: string;
    startDate: string;
    endDate: string;
    description?: string;
}

export interface Job {
    id: string;
    title: string;
    company: string;
    location: string;
    type: string;
    salaryMin?: number;
    salaryMax?: number;
    postedAt: string;
    description?: string;
    requirements?: string;
    benefits?: string;
    skills: string[];
    applicants: number;
    featured: boolean;
    employerId: string;
    status: 'draft' | 'published' | 'expired' | 'archived' | 'paused' | 'closed';
    expiresAt?: string;
    currency?: string;
}

export interface Application {
    id: string;
    jobId: string;
    candidateId: string;
    status: 'pending' | 'reviewing' | 'interview' | 'rejected' | 'accepted' | 'withdrawn' | 'offered';
    appliedAt: string;
    updatedAt: string;
    coverLetter?: string;
    resumeUrl?: string;
    cvLink?: string;
    yearsOfExperience?: number;
    notes?: string;
}

export interface Database {
    users: User[];
    jobs: Job[];
    applications: Application[];
}

// Type aliases for backward compatibility
export type Education = EducationEntry;
export type Experience = WorkExperience;

// === Prisma-backed compatibility layer ===

// In-memory cache to avoid re-fetching everything on every page load
let _cache: Database | null = null;
let _cacheTime = 0;
const CACHE_TTL_MS = 30_000; // 30 seconds

async function readFromPrisma(): Promise<Database> {
    // Return cached data if still fresh
    if (_cache && Date.now() - _cacheTime < CACHE_TTL_MS) {
        return _cache;
    }

    const [rawUsers, rawJobs, rawApplications] = await Promise.all([
        prisma.user.findMany({
            include: {
                profile: true,
                skills: { include: { skill: true } },
                experiences: { orderBy: { start_date: 'desc' } },
                education: { orderBy: { end_date: 'desc' } },
                saved_jobs: true,
            }
        }),
        prisma.job.findMany({
            include: {
                skills: { include: { skill: true } }
            },
            orderBy: { posted_at: 'desc' },
        }),
        prisma.application.findMany({
            orderBy: { applied_at: 'desc' },
        }),
    ]);

    const users: User[] = rawUsers.map(u => ({
        id: u.id,
        email: u.email,
        passwordHash: u.password_hash,
        role: u.role as User['role'],
        name: u.name,
        firstName: u.first_name || undefined,
        lastName: u.last_name || undefined,
        avatarUrl: u.avatar_url || undefined,
        bio: u.profile?.bio || undefined,
        aboutMe: u.profile?.about_me || undefined,
        skills: u.skills.map(us => us.skill.name),
        title: u.profile?.headline || undefined,
        company: u.profile?.company_name || undefined,
        location: u.profile?.location || undefined,
        phone: u.profile?.phone || undefined,
        resumeUrl: u.profile?.resume_url || undefined,
        coverLetter: u.profile?.cover_letter || undefined,
        portfolioUrl: u.profile?.portfolio_url || undefined,
        linkedIn: u.profile?.linkedin_url || undefined,
        github: u.profile?.github_url || undefined,
        website: u.profile?.website_url || undefined,
        companyWebsite: u.profile?.company_website || undefined,
        companySize: u.profile?.company_size || undefined,
        companyIndustry: u.profile?.company_industry || undefined,
        companyLogo: u.profile?.company_logo_url || undefined,
        companyDescription: u.profile?.company_description || undefined,
        description: u.profile?.bio || u.profile?.company_description || undefined,
        savedJobIds: u.saved_jobs.map(sj => sj.job_id),
        experience: u.experiences.map(exp => ({
            id: exp.id,
            title: exp.title,
            company: exp.company,
            location: exp.location || undefined,
            startDate: exp.start_date.toISOString(),
            endDate: exp.end_date?.toISOString(),
            current: exp.is_current,
            description: exp.description || undefined,
        })),
        education: u.education.map(edu => ({
            id: edu.id,
            institution: edu.institution,
            degree: edu.degree,
            field: edu.field || '',
            startDate: edu.start_date?.toISOString() || '',
            endDate: edu.end_date?.toISOString() || '',
            description: edu.description || undefined,
        })),
        createdAt: u.created_at.toISOString(),
    }));

    const jobs: Job[] = rawJobs.map(j => ({
        id: j.id,
        title: j.title,
        company: j.company,
        location: [j.city, j.state, j.country].filter(Boolean).join(", ") || j.work_location_type || "Remote",
        type: j.type,
        salaryMin: j.salary_min || undefined,
        salaryMax: j.salary_max || undefined,
        postedAt: j.posted_at.toISOString(),
        description: j.description || undefined,
        requirements: Array.isArray(j.required_qualifications) ? j.required_qualifications.join(", ") : undefined,
        benefits: Array.isArray(j.benefits) ? j.benefits.join(", ") : undefined,
        skills: j.skills.map(js => js.skill.name),
        applicants: j.applicant_count,
        featured: j.is_featured,
        employerId: j.employer_id,
        status: (j.status as Job['status']) || 'draft',
        expiresAt: j.deadline?.toISOString(),
        currency: j.currency,
    }));

    const applications: Application[] = rawApplications.map(a => ({
        id: a.id,
        jobId: a.job_id,
        candidateId: a.candidate_id,
        status: a.status as Application['status'],
        appliedAt: a.applied_at.toISOString(),
        updatedAt: a.updated_at.toISOString(),
        coverLetter: a.cover_letter || undefined,
        resumeUrl: a.resume_url || undefined,
        cvLink: a.cv_link || undefined,
        yearsOfExperience: a.years_of_experience || undefined,
        notes: a.notes || undefined,
    }));

    const result = { users, jobs, applications };
    _cache = result;
    _cacheTime = Date.now();
    return result;
}

/** Invalidate the in-memory cache (call after any write operation) */
export function invalidateDbCache() {
    _cache = null;
    _cacheTime = 0;
}

/**
 * Backward-compatible db object.
 * - `db.read()` now returns a Promise (callers must await)
 * - `db.write()` is a no-op (all writes go through Prisma actions now)
 */
export const db = {
    read: readFromPrisma,
    write: async (_data: Database) => {
        invalidateDbCache();
        console.warn('db.write() is deprecated. All writes now go through Prisma server actions.');
    },
};
