"use server";

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

// ─────────────────────────────────────────────────────────────────────────────
// UPDATE AVATAR
// ─────────────────────────────────────────────────────────────────────────────
export async function updateAvatarUrl(url: string) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    try {
        await prisma.user.update({
            where: { id: user.id },
            data: { avatar_url: url },
        });
        revalidatePath("/dashboard");
        revalidatePath("/dashboard/profile");
        return { success: true };
    } catch (error) {
        console.error("Failed to update avatar:", error);
        return { error: "Failed to update avatar" };
    }
}

// Keep the original action for backward compatibility
export async function updateProfileAction(formData: FormData) {
    const userId = formData.get("userId") as string;
    if (!userId) throw new Error("User ID is required");

    const rawSkills = formData.get("skills") as string;
    const skills = rawSkills ? rawSkills.split(",").map((s) => s.trim()).filter(Boolean) : [];

    const name = formData.get("name") as string;
    if (name) await prisma.user.update({ where: { id: userId }, data: { name } });

    await prisma.profile.upsert({
        where: { user_id: userId },
        update: {
            headline: (formData.get("title") as string) || undefined,
            bio: (formData.get("bio") as string) || undefined,
            company_name: (formData.get("company") as string) || undefined,
        },
        create: {
            user_id: userId,
            headline: (formData.get("title") as string) || undefined,
            bio: (formData.get("bio") as string) || undefined,
            company_name: (formData.get("company") as string) || undefined,
        },
    });

    await prisma.userSkill.deleteMany({ where: { user_id: userId } });
    for (const skillName of skills) {
        const skill = await prisma.skill.upsert({ where: { name: skillName }, update: {}, create: { name: skillName } });
        await prisma.userSkill.create({ data: { user_id: userId, skill_id: skill.id } });
    }

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

// ─────────────────────────────────────────────────────────────────────────────
// UPDATE CANDIDATE PROFILE
// ─────────────────────────────────────────────────────────────────────────────
export async function updateCandidateProfile(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const headline = (formData.get("headline") as string) || "";
    const location = (formData.get("location") as string) || "";
    const bio = (formData.get("bio") as string) || "";
    const phone = (formData.get("phone") as string) || "";
    const portfolio_url = (formData.get("portfolio_url") as string) || "";
    const linkedin_url = (formData.get("linkedin_url") as string) || "";
    const github_url = (formData.get("github_url") as string) || "";
    const resume_url = (formData.get("resume_url") as string) || "";
    const salary = (formData.get("salary") as string) || "";
    const jobTypesRaw = formData.get("jobTypes") as string;
    const jobTypes: string[] = jobTypesRaw ? JSON.parse(jobTypesRaw) : [];

    await prisma.profile.upsert({
        where: { user_id: user.id },
        create: { user_id: user.id, headline, location, bio, phone, portfolio_url, linkedin_url, github_url, resume_url, salary_expectation: salary, job_types: jobTypes },
        update: { headline, location, bio, phone, portfolio_url, linkedin_url, github_url, resume_url, salary_expectation: salary, job_types: jobTypes },
    });

    revalidatePath("/dashboard/profile");
    revalidatePath("/dashboard");
    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// UPDATE SKILLS
// ─────────────────────────────────────────────────────────────────────────────
export async function updateSkills(skills: string[]) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    await prisma.userSkill.deleteMany({ where: { user_id: user.id } });
    for (const name of skills) {
        const skill = await prisma.skill.upsert({ where: { name }, create: { name }, update: {} });
        await prisma.userSkill.create({ data: { user_id: user.id, skill_id: skill.id } });
    }

    revalidatePath("/dashboard/profile");
    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// UPDATE COMPANY PROFILE (employer)
// ─────────────────────────────────────────────────────────────────────────────
export async function updateCompanyProfile(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const company_name = (formData.get("company_name") as string) || "";
    const company_website = (formData.get("company_website") as string) || "";
    const company_location = (formData.get("company_location") as string) || "";
    const company_industry = (formData.get("company_industry") as string) || "";
    const company_size = (formData.get("company_size") as string) || "";
    const company_description = (formData.get("company_description") as string) || "";
    const company_logo_url = (formData.get("company_logo_url") as string) || "";
    const hiringForRaw = formData.get("hiring_for") as string;
    const hiring_for: string[] = hiringForRaw ? JSON.parse(hiringForRaw) : [];

    await prisma.profile.upsert({
        where: { user_id: user.id },
        create: { user_id: user.id, company_name, company_website, company_location, company_industry, company_size, company_description, hiring_for, company_logo_url },
        update: { company_name, company_website, company_location, company_industry, company_size, company_description, hiring_for, company_logo_url },
    });

    revalidatePath("/dashboard/employer/company");
    revalidatePath("/dashboard");
    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// UPDATE PERSONAL INFO
// ─────────────────────────────────────────────────────────────────────────────
export async function updatePersonalInfo(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const first_name = (formData.get("first_name") as string)?.trim();
    const last_name = (formData.get("last_name") as string)?.trim();
    if (!first_name || !last_name) return { error: "Name fields are required" };

    await prisma.user.update({
        where: { id: user.id },
        data: { first_name, last_name, name: `${first_name} ${last_name}` },
    });

    revalidatePath("/dashboard/settings");
    revalidatePath("/dashboard");
    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// CHANGE PASSWORD
// ─────────────────────────────────────────────────────────────────────────────
export async function changePassword(formData: FormData) {
    const { verifyPassword, hashPassword } = await import("@/lib/password");
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const currentPassword = formData.get("current_password") as string;
    const newPassword = formData.get("new_password") as string;
    const confirmPassword = formData.get("confirm_password") as string;

    if (!currentPassword || !newPassword || !confirmPassword) return { error: "All fields are required" };
    if (newPassword !== confirmPassword) return { error: "New passwords do not match" };

    const passwordRegex = /^(?=.*[A-Z])(?=.*\d).{8,}$/;
    if (!passwordRegex.test(newPassword)) return { error: "Password must be at least 8 characters with one uppercase and one number." };

    const dbUser = await prisma.user.findUnique({ where: { id: user.id } });
    if (!dbUser?.password_hash) return { error: "This account uses social login — no password to change." };

    const isValid = await verifyPassword(currentPassword, dbUser.password_hash);
    if (!isValid) return { error: "Current password is incorrect" };

    const hashedPassword = await hashPassword(newPassword);
    await prisma.user.update({ where: { id: user.id }, data: { password_hash: hashedPassword } });

    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// WORK EXPERIENCE CRUD
// ─────────────────────────────────────────────────────────────────────────────
export async function addExperience(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const title = (formData.get("title") as string)?.trim();
    const company = (formData.get("company") as string)?.trim();
    const startDateStr = formData.get("start_date") as string;

    if (!title || !company || !startDateStr) return { error: "Title, company, and start date are required" };

    const exp = await prisma.experience.create({
        data: {
            user_id: user.id,
            title,
            company,
            location: (formData.get("location") as string) || undefined,
            start_date: new Date(startDateStr),
            end_date: formData.get("end_date") ? new Date(formData.get("end_date") as string) : null,
            is_current: formData.get("is_current") === "true",
            description: (formData.get("description") as string) || undefined,
        },
    });

    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true, id: exp.id };
}

export async function updateExperience(id: string, formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    // Ownership check
    const exp = await prisma.experience.findUnique({ where: { id } });
    if (!exp || exp.user_id !== user.id) return { error: "Not found" };

    const startDateStr = formData.get("start_date") as string;

    await prisma.experience.update({
        where: { id },
        data: {
            title: (formData.get("title") as string)?.trim() || exp.title,
            company: (formData.get("company") as string)?.trim() || exp.company,
            location: (formData.get("location") as string) || undefined,
            start_date: startDateStr ? new Date(startDateStr) : exp.start_date,
            end_date: formData.get("end_date") ? new Date(formData.get("end_date") as string) : null,
            is_current: formData.get("is_current") === "true",
            description: (formData.get("description") as string) || undefined,
        },
    });

    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true };
}

export async function deleteExperience(id: string) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const exp = await prisma.experience.findUnique({ where: { id } });
    if (!exp || exp.user_id !== user.id) return { error: "Not found" };

    await prisma.experience.delete({ where: { id } });
    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true };
}

// ─────────────────────────────────────────────────────────────────────────────
// EDUCATION CRUD
// ─────────────────────────────────────────────────────────────────────────────
export async function addEducation(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const degree = (formData.get("degree") as string)?.trim();
    const institution = (formData.get("institution") as string)?.trim();

    if (!degree || !institution) return { error: "Degree and institution are required" };

    const edu = await prisma.education.create({
        data: {
            user_id: user.id,
            degree,
            institution,
            field: (formData.get("field") as string) || undefined,
            start_date: formData.get("start_date") ? new Date(formData.get("start_date") as string) : null,
            end_date: formData.get("end_date") ? new Date(formData.get("end_date") as string) : null,
            description: (formData.get("description") as string) || undefined,
        },
    });

    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true, id: edu.id };
}

export async function updateEducation(id: string, formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const edu = await prisma.education.findUnique({ where: { id } });
    if (!edu || edu.user_id !== user.id) return { error: "Not found" };

    await prisma.education.update({
        where: { id },
        data: {
            degree: (formData.get("degree") as string)?.trim() || edu.degree,
            institution: (formData.get("institution") as string)?.trim() || edu.institution,
            field: (formData.get("field") as string) || undefined,
            start_date: formData.get("start_date") ? new Date(formData.get("start_date") as string) : null,
            end_date: formData.get("end_date") ? new Date(formData.get("end_date") as string) : null,
            description: (formData.get("description") as string) || undefined,
        },
    });

    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true };
}

export async function deleteEducation(id: string) {
    const user = await getCurrentUser();
    if (!user) return { error: "Not authenticated" };

    const edu = await prisma.education.findUnique({ where: { id } });
    if (!edu || edu.user_id !== user.id) return { error: "Not found" };

    await prisma.education.delete({ where: { id } });
    revalidatePath("/dashboard/profile/edit");
    revalidatePath("/dashboard/profile/view");
    revalidatePath("/dashboard");
    return { success: true };
}

