"use server";

import { getSupabaseClient } from "./supabase";

export type SnapshotType = "planned" | "live" | "final";

// Get the whiteboard record for a lesson
export const getLessonWhiteboard = async (lessonId: number) => {
    try {
        const supabase = await getSupabaseClient();
        const { data, error } = await supabase
            .from("LessonWhiteboard")
            .select("*")
            .eq("lessonId", lessonId)
            .single();

        // TODO: This doesn't feel right...
        if (error) {
            if (error.code === "PGRST116") {
                // No whiteboard exists yet for this lesson. Try to create one lazily.
                const { data: created, error: createError } = await supabase
                    .from("LessonWhiteboard")
                    .insert({ lessonId })
                    .select()
                    .single();

                if (createError) {
                    console.error("Failed to create LessonWhiteboard record:", createError);
                    return { success: false, data: null };
                }

                return { success: true, data: created };
            }
            throw error;
        }
        return { success: true, data };
    } catch (err) {
        console.error("Failed to fetch whiteboard:", err);
        return { success: false, data: null };
    }
};

// Save a specific snapshot state (planned, live, or final)
export const saveLessonSnapshot = async (
    lessonId: number,
    snapshotType: SnapshotType,
    snapshotData: any
) => {
    try {
        const supabase = await getSupabaseClient();

        const updatePayload: Record<string, any> = {};
        if (snapshotType === "planned") updatePayload.plannedSnapshotData = snapshotData;
        if (snapshotType === "live") updatePayload.liveSnapshotData = snapshotData;
        if (snapshotType === "final") updatePayload.finalSnapshotData = snapshotData;

        const { error } = await supabase
            .from("LessonWhiteboard")
            .update(updatePayload)
            .eq("lessonId", lessonId);

        if (error) throw error;
        return { success: true };
    } catch (err) {
        console.error("Failed to save snapshot:", err);
        return { success: false };
    }
};

// Duplicate a planned snapshot to a new lesson
export const duplicateLessonPlan = async (sourceLessonId: number, targetLessonId: number) => {
    try {
        const supabase = await getSupabaseClient();

        const { data: sourceBoard, error: fetchError } = await supabase
            .from("LessonWhiteboard")
            .select("plannedSnapshotData")
            .eq("lessonId", sourceLessonId)
            .single();

        if (fetchError) throw fetchError;
        if (!sourceBoard?.plannedSnapshotData) throw new Error("No planned snapshot found to copy.");

        const { error: updateError } = await supabase
            .from("LessonWhiteboard")
            .update({ plannedSnapshotData: sourceBoard.plannedSnapshotData })
            .eq("lessonId", targetLessonId);

        if (updateError) throw updateError;
        return { success: true };
    } catch (err) {
        console.error("Failed to duplicate lesson plan:", err);
        return { success: false };
    }
};
