import { PRIVATE_PHOTO_UPLOAD_DIR } from '$env/static/private';
import type { Actions, ServerLoad } from '@sveltejs/kit';
import { LocalFileRepository } from '$lib/LocalFileRepository.js';

export const load: ServerLoad = async ({ locals }) => {
    const photos = await locals.prisma.photoPost.findMany({
        select: {
            id: true,
            filePath: true,
            fileName: true,
            title: true,
            description: true,
            createdAt: true,
        },
    });
    return { photos };
};

export const actions = {
    default: async ({ request, locals }) => {
        const formData = await request.formData();
        const file = formData.get('file') as File;
        const title = formData.get('title') as string;
        const description = formData.get('description') as string;

        const fileRepo = new LocalFileRepository(PRIVATE_PHOTO_UPLOAD_DIR);
        const { fileName, filePath } = await fileRepo.saveFile(file);

        await locals.prisma.photoPost.create({
            data: {
                fileName,
                filePath,
                title,
                description,
                createdAt: new Date(),
            },
        });

        return { success: true };
    },
} satisfies Actions;
