"use server";

import prisma from "@/lib/prisma";
import { revalidatePath } from "next/cache";

/**
 * Update candidate's basic profile information
 */
export async function updateCandidateProfile(
    userId: string,
    profileData: {
        name?: string;
        title?: string;
        location?: string;
        phone?: string;
        bio?: string;
        aboutMe?: string;
        portfolioUrl?: string;
        resumeUrl?: string;
        coverLetter?: string;
        linkedIn?: string;
        github?: string;
        website?: string;
        twitter?: string;
    }
) {
    try {
        // Update user name if provided
        if (profileData.name) {
            await prisma.user.update({
                where: { id: userId },
                data: { name: profileData.name }
            });
        }

        // Upsert profile
        await prisma.profile.upsert({
            where: { user_id: userId },
            update: {
                headline: profileData.title,
                location: profileData.location,
                phone: profileData.phone,
                bio: profileData.bio,
                about_me: profileData.aboutMe,
                portfolio_url: profileData.portfolioUrl,
                resume_url: profileData.resumeUrl,
                cover_letter: profileData.coverLetter,
                linkedin_url: profileData.linkedIn,
                github_url: profileData.github,
                website_url: profileData.website,
                twitter_url: profileData.twitter,
            },
            create: {
                user_id: userId,
                headline: profileData.title,
                location: profileData.location,
                phone: profileData.phone,
                bio: profileData.bio,
                about_me: profileData.aboutMe,
                portfolio_url: profileData.portfolioUrl,
                resume_url: profileData.resumeUrl,
                cover_letter: profileData.coverLetter,
                linkedin_url: profileData.linkedIn,
                github_url: profileData.github,
                website_url: profileData.website,
                twitter_url: profileData.twitter,
            }
        });

        revalidatePath("/dashboard/profile");
        revalidatePath("/dashboard");

        return { success: true };
    } catch (error) {
        console.error("Failed to update profile:", error);
        return { success: false, error: "Failed to update profile" };
    }
}

/**
 * Add new work experience entry
 */
export async function addWorkExperience(userId: string, experience: {
    title: string;
    company: string;
    location?: string;
    startDate: string;
    endDate?: string;
    description?: string;
    current?: boolean;
}) {
    try {
        const newExperience = await prisma.experience.create({
            data: {
                user_id: userId,
                title: experience.title,
                company: experience.company,
                location: experience.location,
                start_date: new Date(experience.startDate),
                end_date: experience.endDate ? new Date(experience.endDate) : null,
                is_current: experience.current || false,
                description: experience.description,
            }
        });

        revalidatePath("/dashboard/profile");

        return {
            success: true,
            experience: {
                id: newExperience.id,
                title: newExperience.title,
                company: newExperience.company,
                location: newExperience.location ?? undefined,
                startDate: newExperience.start_date.toISOString(),
                endDate: newExperience.end_date?.toISOString(),
                current: newExperience.is_current,
                description: newExperience.description ?? undefined,
            }
        };
    } catch (error) {
        console.error("Failed to add work experience:", error);
        return { success: false, error: "Failed to add work experience" };
    }
}

/**
 * Update existing work experience entry
 */
export async function updateWorkExperience(
    userId: string,
    experienceId: string,
    updates: {
        title?: string;
        company?: string;
        location?: string;
        startDate?: string;
        endDate?: string;
        description?: string;
        current?: boolean;
    }
) {
    try {
        // Verify ownership
        const exp = await prisma.experience.findFirst({
            where: { id: experienceId, user_id: userId }
        });

        if (!exp) {
            return { success: false, error: "Experience not found" };
        }

        await prisma.experience.update({
            where: { id: experienceId },
            data: {
                title: updates.title,
                company: updates.company,
                location: updates.location,
                start_date: updates.startDate ? new Date(updates.startDate) : undefined,
                end_date: updates.endDate ? new Date(updates.endDate) : undefined,
                is_current: updates.current,
                description: updates.description,
            }
        });

        revalidatePath("/dashboard/profile");
        return { success: true };
    } catch (error) {
        console.error("Failed to update work experience:", error);
        return { success: false, error: "Failed to update work experience" };
    }
}

/**
 * Delete work experience entry
 */
export async function deleteWorkExperience(userId: string, experienceId: string) {
    try {
        // Verify ownership
        const exp = await prisma.experience.findFirst({
            where: { id: experienceId, user_id: userId }
        });

        if (!exp) {
            return { success: false, error: "Experience not found" };
        }

        await prisma.experience.delete({
            where: { id: experienceId }
        });

        revalidatePath("/dashboard/profile");
        return { success: true };
    } catch (error) {
        console.error("Failed to delete work experience:", error);
        return { success: false, error: "Failed to delete work experience" };
    }
}

/**
 * Add new education entry
 */
export async function addEducation(userId: string, education: {
    institution: string;
    degree: string;
    field: string;
    startDate: string;
    endDate: string;
    description?: string;
}) {
    try {
        const newEducation = await prisma.education.create({
            data: {
                user_id: userId,
                institution: education.institution,
                degree: education.degree,
                field: education.field,
                start_date: new Date(education.startDate),
                end_date: new Date(education.endDate),
                description: education.description,
            }
        });

        revalidatePath("/dashboard/profile");
        return {
            success: true,
            education: {
                id: newEducation.id,
                institution: newEducation.institution,
                degree: newEducation.degree,
                field: newEducation.field || '',
                startDate: newEducation.start_date?.toISOString() || '',
                endDate: newEducation.end_date?.toISOString() || '',
                description: newEducation.description ?? undefined,
            }
        };
    } catch (error) {
        console.error("Failed to add education:", error);
        return { success: false, error: "Failed to add education" };
    }
}

/**
 * Update existing education entry
 */
export async function updateEducation(
    userId: string,
    educationId: string,
    updates: {
        institution?: string;
        degree?: string;
        field?: string;
        startDate?: string;
        endDate?: string;
        description?: string;
    }
) {
    try {
        const edu = await prisma.education.findFirst({
            where: { id: educationId, user_id: userId }
        });

        if (!edu) {
            return { success: false, error: "Education not found" };
        }

        await prisma.education.update({
            where: { id: educationId },
            data: {
                institution: updates.institution,
                degree: updates.degree,
                field: updates.field,
                start_date: updates.startDate ? new Date(updates.startDate) : undefined,
                end_date: updates.endDate ? new Date(updates.endDate) : undefined,
                description: updates.description,
            }
        });

        revalidatePath("/dashboard/profile");
        return { success: true };
    } catch (error) {
        console.error("Failed to update education:", error);
        return { success: false, error: "Failed to update education" };
    }
}

/**
 * Delete education entry
 */
export async function deleteEducation(userId: string, educationId: string) {
    try {
        const edu = await prisma.education.findFirst({
            where: { id: educationId, user_id: userId }
        });

        if (!edu) {
            return { success: false, error: "Education not found" };
        }

        await prisma.education.delete({
            where: { id: educationId }
        });

        revalidatePath("/dashboard/profile");
        return { success: true };
    } catch (error) {
        console.error("Failed to delete education:", error);
        return { success: false, error: "Failed to delete education" };
    }
}

/**
 * Update skills array
 */
export async function updateSkills(userId: string, skills: string[]) {
    try {
        // Delete existing user skills
        await prisma.userSkill.deleteMany({
            where: { user_id: userId }
        });

        // Upsert each skill and create user_skill links
        for (const skillName of skills) {
            const skill = await prisma.skill.upsert({
                where: { name: skillName.trim() },
                update: {},
                create: { name: skillName.trim() },
            });

            await prisma.userSkill.create({
                data: {
                    user_id: userId,
                    skill_id: skill.id,
                }
            });
        }

        revalidatePath("/dashboard/profile");
        revalidatePath("/dashboard");
        return { success: true };
    } catch (error) {
        console.error("Failed to update skills:", error);
        return { success: false, error: "Failed to update skills" };
    }
}

/**
 * Update employer's profile information
 */
export async function updateEmployerProfile(
    userId: string,
    profileData: {
        name?: string;
        companyName?: string;
        companyWebsite?: string;
        companySize?: string;
        companyIndustry?: string;
        companyLogoUrl?: string;
        companyDescription?: string;
        location?: string;
        phone?: string;
        linkedIn?: string;
        twitter?: string;
    }
) {
    try {
        if (profileData.name) {
            await prisma.user.update({
                where: { id: userId },
                data: { name: profileData.name }
            });
        }

        await prisma.profile.upsert({
            where: { user_id: userId },
            update: {
                company_name: profileData.companyName,
                company_website: profileData.companyWebsite,
                company_size: profileData.companySize,
                company_industry: profileData.companyIndustry,
                company_logo_url: profileData.companyLogoUrl,
                company_description: profileData.companyDescription,
                location: profileData.location,
                phone: profileData.phone,
                linkedin_url: profileData.linkedIn,
                twitter_url: profileData.twitter,
            },
            create: {
                user_id: userId,
                company_name: profileData.companyName,
                company_website: profileData.companyWebsite,
                company_size: profileData.companySize,
                company_industry: profileData.companyIndustry,
                company_logo_url: profileData.companyLogoUrl,
                company_description: profileData.companyDescription,
                location: profileData.location,
                phone: profileData.phone,
                linkedin_url: profileData.linkedIn,
                twitter_url: profileData.twitter,
            }
        });

        revalidatePath("/dashboard/employer/profile");
        revalidatePath("/dashboard/employer");

        return { success: true };
    } catch (error) {
        console.error("Failed to update employer profile:", error);
        return { success: false, error: "Failed to update employer profile" };
    }
}
