import { error, redirect, type Actions } from "@sveltejs/kit";
import type { PageServerLoad } from "./$types.js";
import { LocalFileRepository } from "$lib/LocalFileRepository.js";
import { PRIVATE_PHOTO_UPLOAD_DIR } from "$env/static/private";
import type { Prisma } from "../../../../../generated/prisma/client.js";

export const load: PageServerLoad = async ({ params, locals }) => {
  const { id } = params;

  const photo = await locals.prisma.photoPost.findFirst({
    where: {
      id: Number(id),
    },
  });

  if (!photo) {
    return error(404, { message: `Photo with ID ${id} not found` });
  }

  return { photo };
};

export const actions = {
  update: async ({ request, locals, params }) => {
    const formData = await request.formData();
    const { id } = params;

    const fileRepo = new LocalFileRepository(PRIVATE_PHOTO_UPLOAD_DIR);

    const title = formData.get("title") as string;
    const description = formData.get("description") as string;
    const file = formData.get("file") as File | null;

    const options: Prisma.PhotoPostUpdateInput = {
      title,
      description,
    };

    if (file && file.size > 0) {
      const saveResult = await fileRepo.saveFile(file);
      options.fileName = saveResult.fileName;
      options.filePath = saveResult.filePath;
    }

    await locals.prisma.photoPost.update({
      where: { id: Number(id) },
      data: options,
    });

    return { success: true };
  },
  delete: async ({ locals, params }) => {
    const { id } = params;
    const photoId = Number(id);
    const fileRepo = new LocalFileRepository(PRIVATE_PHOTO_UPLOAD_DIR);

    const photo = await locals.prisma.photoPost.findUnique({
      where: { id: photoId },
      select: {
        id: true,
        filePath: true,
      },
    });

    if (!photo) {
      return error(404, { message: `Photo with ID ${id} not found` });
    }

    await locals.prisma.photoPost.delete({
      where: { id: photoId },
    });

    await fileRepo.deleteFile(photo.filePath);

    throw redirect(303, "/admin/photos");
  },
} satisfies Actions;
