import { error, fail, redirect } from '@sveltejs/kit';
import { deactivatePart, getPart, listCategories, updatePart } from '$lib/server/parts.js';
import { recentMovementsForPart } from '$lib/server/movements.js';

export function load({ params }) {
  const id = Number(params.id);
  const part = getPart(id);
  if (!part) throw error(404, 'Part not found');
  return {
    part,
    categories: listCategories(),
    movements: recentMovementsForPart(id, 25)
  };
}

export const actions = {
  update: async ({ request, params }) => {
    const id = Number(params.id);
    const form = await request.formData();
    const data = Object.fromEntries(form);

    const errors = {};
    if ((!data.name_en || !data.name_en.trim()) && (!data.name_tg || !data.name_tg.trim())) {
      errors.name = 'parts.errors.name_required';
    }
    if (Object.keys(errors).length) return fail(400, { errors, values: data });

    updatePart(id, data);
    throw redirect(303, `/parts/${id}`);
  },

  delete: async ({ params }) => {
    deactivatePart(Number(params.id));
    throw redirect(303, '/parts');
  }
};
