"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";
import { hashPassword, verifyPassword } from "@/lib/password";
import { EmailService } from "@/services/EmailService";
import crypto from "crypto";
import { encryptSession, SESSION_COOKIE_NAME } from "@/lib/session";

// --------------------------------------------------------------------------
// LOGIN
// --------------------------------------------------------------------------
export async function login(formData: FormData) {
    const email = formData.get("email") as string;
    const password = formData.get("password") as string;
    const rememberMe = formData.get("rememberMe") === "true";

    if (!email || !password) {
        return { error: "Email and password are required" };
    }

    const user = await prisma.user.findUnique({ where: { email } });

    if (!user) {
        return { error: "Invalid email or password" };
    }

    // If user registered via OAuth they may not have a password
    if (!user.password_hash) {
        return { error: `This account uses ${user.auth_provider} sign-in. Please use the social login button.` };
    }

    const isValid = await verifyPassword(password, user.password_hash);
    if (!isValid) {
        return { error: "Invalid email or password" };
    }

    // Update last login
    await prisma.user.update({
        where: { id: user.id },
        data: { last_login_at: new Date() }
    });

    const maxAge = rememberMe ? 30 * 24 * 60 * 60 : 7 * 24 * 60 * 60;
    const expiresAt = new Date(Date.now() + maxAge * 1000);

    const sessionToken = await encryptSession({ userId: user.id, role: user.role, expiresAt });

    const cookieStore = await cookies();
    cookieStore.set(SESSION_COOKIE_NAME, sessionToken, {
        path: "/",
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        expires: expiresAt,
    });

    if (user.role === "admin") redirect("/admin");

    // Redirect to onboarding if not yet completed
    if (!user.onboarding_completed) {
        redirect(`/onboarding/${user.role}`);
    }

    redirect("/dashboard");
}

// --------------------------------------------------------------------------
// SIGNUP
// --------------------------------------------------------------------------
export async function signup(formData: FormData) {
    const first_name = (formData.get("first_name") as string)?.trim();
    const last_name = (formData.get("last_name") as string)?.trim();
    const email = formData.get("email") as string;
    const password = formData.get("password") as string;
    const role = formData.get("role") as "candidate" | "employer";

    if (!first_name || !last_name || !email || !password || !role) {
        return { error: "All fields are required" };
    }

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

    const existingUser = await prisma.user.findUnique({ where: { email } });
    if (existingUser) {
        return { error: "An account with this email already exists." };
    }

    const hashedPassword = await hashPassword(password);
    const verificationToken = crypto.randomBytes(32).toString("hex");
    const tokenExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000);

    const newUser = await prisma.user.create({
        data: {
            name: `${first_name} ${last_name}`,
            first_name,
            last_name,
            email,
            password_hash: hashedPassword,
            role,
            auth_provider: "credentials",
            onboarding_completed: false,
            verification_token: verificationToken,
            verification_token_expiry: tokenExpiry,
            profile: { create: {} }
        }
    });

    // Send verification email (non-blocking)
    try {
        await EmailService.sendVerificationEmail(email, verificationToken);
    } catch (e) {
        console.error("Failed to send verification email:", e);
    }

    // Create session immediately so they can proceed to onboarding
    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    const sessionToken = await encryptSession({ userId: newUser.id, role: newUser.role, expiresAt });

    const cookieStore = await cookies();
    cookieStore.set(SESSION_COOKIE_NAME, sessionToken, {
        path: "/",
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        expires: expiresAt,
    });

    redirect(`/onboarding/${role}`);
}

// --------------------------------------------------------------------------
// SOCIAL AUTH CALLBACK — called from /api/auth/callback
// Creates or finds a user from OAuth data and starts a session
// --------------------------------------------------------------------------
export async function handleSocialCallback({
    email,
    first_name,
    last_name,
    provider,
    provider_id,
}: {
    email: string;
    first_name: string;
    last_name: string;
    provider: string;
    provider_id: string;
}) {
    // Find existing user by email or provider_id
    let user = await prisma.user.findFirst({
        where: {
            OR: [{ email }, { provider_id }]
        }
    });

    if (!user) {
        // New social user — needs role selection
        // We'll create a provisional "candidate" account; role can be updated on /auth/role
        user = await prisma.user.create({
            data: {
                name: `${first_name} ${last_name}`,
                first_name,
                last_name,
                email,
                password_hash: "", // No password for social users
                role: "candidate",  // Default, updated on role-selection page
                auth_provider: provider,
                provider_id,
                onboarding_completed: false,
                profile: { create: {} }
            }
        });

        // Create session and redirect to role selection
        const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
        const sessionToken = await encryptSession({ userId: user.id, role: user.role, expiresAt });

        const cookieStore = await cookies();
        cookieStore.set(SESSION_COOKIE_NAME, sessionToken, {
            path: "/",
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            sameSite: "lax",
            expires: expiresAt,
        });

        redirect("/auth/role");
    }

    // Existing user — update last login
    await prisma.user.update({
        where: { id: user.id },
        data: { last_login_at: new Date(), provider_id }
    });

    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    const sessionToken = await encryptSession({ userId: user.id, role: user.role, expiresAt });

    const cookieStore = await cookies();
    cookieStore.set(SESSION_COOKIE_NAME, sessionToken, {
        path: "/",
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        expires: expiresAt,
    });

    if (!user.onboarding_completed) {
        redirect(`/onboarding/${user.role}`);
    }

    redirect("/dashboard");
}

// --------------------------------------------------------------------------
// SET ROLE (after social login)
// --------------------------------------------------------------------------
export async function setUserRole(formData: FormData) {
    const role = formData.get("role") as "candidate" | "employer";
    const userId = formData.get("userId") as string;

    if (!role || !userId) return { error: "Missing required fields" };

    await prisma.user.update({
        where: { id: userId },
        data: { role }
    });

    // Refresh session with new role
    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    const sessionToken = await encryptSession({ userId, role, expiresAt });

    const cookieStore = await cookies();
    cookieStore.set(SESSION_COOKIE_NAME, sessionToken, {
        path: "/",
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        expires: expiresAt,
    });

    redirect(`/onboarding/${role}`);
}

// --------------------------------------------------------------------------
// COMPLETE ONBOARDING — saves all wizard data then marks complete
// --------------------------------------------------------------------------
export async function completeOnboarding(formData: FormData) {
    const userId = formData.get("userId") as string;
    const role = formData.get("role") as string;
    if (!userId) return { error: "Not authenticated" };

    if (role === "candidate") {
        const headline = (formData.get("headline") as string) || "";
        const location = (formData.get("location") as string) || "";
        const bio = (formData.get("bio") as string) || "";
        const salary = (formData.get("salary") as string) || "";
        const skillsRaw = formData.get("skills") as string;
        const jobTypesRaw = formData.get("jobTypes") as string;

        const skills: string[] = skillsRaw ? JSON.parse(skillsRaw) : [];
        const jobTypes: string[] = jobTypesRaw ? JSON.parse(jobTypesRaw) : [];

        // Upsert Profile
        await prisma.profile.upsert({
            where: { user_id: userId },
            create: { user_id: userId, headline, location, bio, job_types: jobTypes, salary_expectation: salary },
            update: { headline, location, bio, job_types: jobTypes, salary_expectation: salary },
        });

        // Sync skills — find-or-create each, then upsert UserSkill junction
        for (const name of skills) {
            const skill = await prisma.skill.upsert({
                where: { name },
                create: { name },
                update: {},
            });
            await prisma.userSkill.upsert({
                where: { user_id_skill_id: { user_id: userId, skill_id: skill.id } },
                create: { user_id: userId, skill_id: skill.id },
                update: {},
            });
        }
    }

    if (role === "employer") {
        const companyName = (formData.get("companyName") as string) || "";
        const companyWebsite = (formData.get("companyWebsite") as string) || "";
        const companyLocation = (formData.get("companyLocation") as string) || "";
        const industry = (formData.get("industry") as string) || "";
        const companySize = (formData.get("companySize") as string) || "";
        const companyDescription = (formData.get("companyDescription") as string) || "";
        const hiringForRaw = formData.get("hiringFor") as string;
        const hiringFor: string[] = hiringForRaw ? JSON.parse(hiringForRaw) : [];

        await prisma.profile.upsert({
            where: { user_id: userId },
            create: {
                user_id: userId,
                company_name: companyName,
                company_website: companyWebsite,
                company_location: companyLocation,
                company_industry: industry,
                company_size: companySize,
                company_description: companyDescription,
                hiring_for: hiringFor,
            },
            update: {
                company_name: companyName,
                company_website: companyWebsite,
                company_location: companyLocation,
                company_industry: industry,
                company_size: companySize,
                company_description: companyDescription,
                hiring_for: hiringFor,
            },
        });
    }

    await prisma.user.update({
        where: { id: userId },
        data: { onboarding_completed: true },
    });

    redirect("/dashboard");
}

// --------------------------------------------------------------------------
// LOGOUT
// --------------------------------------------------------------------------
export async function logout() {
    const cookieStore = await cookies();
    cookieStore.delete(SESSION_COOKIE_NAME);
    redirect("/");
}

// --------------------------------------------------------------------------
// PASSWORD RESET (unchanged)
// --------------------------------------------------------------------------
export async function requestPasswordReset(email: string): Promise<{ success: boolean; error?: string }> {
    const user = await prisma.user.findUnique({ where: { email } });
    if (!user) return { success: true }; // Don't reveal existence

    const resetToken = crypto.randomUUID();
    const resetTokenExpiry = new Date(Date.now() + 3600000);

    await prisma.user.update({
        where: { id: user.id },
        data: { reset_token: resetToken, reset_token_expiry: resetTokenExpiry }
    });

    try {
        await EmailService.sendPasswordResetEmail(email, resetToken);
    } catch (e) {
        console.error("Failed to send password reset email:", e);
    }
    return { success: true };
}

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

    const user = await prisma.user.findFirst({
        where: { reset_token: token, reset_token_expiry: { gt: new Date() } }
    });

    if (!user) return { error: "Invalid or expired reset token" };

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

    return { success: true };
}
