import { client } from "$lib/server/lucia";
import { redirect, type Actions, fail, error } from "@sveltejs/kit";
import { ZodError, z } from "zod";

const prisma = client;

export const load = async () => {
    const notReversedposts = await prisma.authPost.findMany();
    const posts = notReversedposts.reverse();

    return {
        posts
    };
};

const createPostSchema = z.object({
    title: z.string({ required_error: '*title is required.' })
        .min(3, { message: '*title must be at least 3 characters long.' })
        .max(12, { message: '*limit for title is 12 characters.' }).trim(),
    content: z.string({ required_error: '*content is required.' })
        .min(2, { message: '*content must be at least 2 characters long.' })
        .max(230, { message: '*limit for content is 25 characters.' }).trim()
})

export const actions: Actions = {
    createPost: async ({ request, locals }) => {
        const { user } = await locals.auth.validateUser();
        if (!user) {
            throw redirect(303, '/login');
        }

        const form = Object.fromEntries(await request.formData());

        try {
            const zform = createPostSchema.parse(form);
            const post = await prisma.authPost.create({
                data: {
                    title: zform.title,
                    content: zform.content,
                    author_id: String(user.userId),
                    author_username: String(user.username)
                },
            });

            return { success: true };

        } catch (e) {
            if (e instanceof ZodError) {
                const { fieldErrors: errors } = e.flatten();

                return fail(422, { errors });
            }

            return fail(500, { message: "There was an error while creating post." });
        }
    },
    deletePost: async ({ request, locals }) => {
        const { user } = await locals.auth.validateUser();
        if (!user) {
            throw redirect(303, '/login');
        }

        const form = await request.formData();
        const postid = form.get("postid");
        const post_author = form.get("post_author");

        if (user.userId !== post_author) {
            throw error(500, { message: "you cannot delete this post." });
        }
        try {
            await prisma.authPost.delete({
                where: {
                    id: Number(postid)
                }
            })
        } catch {
            throw error(500, { message: "Could not delete the post." });
        }
        return { success: true };
    },
};