import { fail, redirect } from '@sveltejs/kit';
import { listParts } from '$lib/server/parts.js';
import { listSuppliers } from '$lib/server/suppliers.js';
import { recordMovement } from '$lib/server/movements.js';

export function load({ url }) {
  return {
    parts:     listParts(),
    suppliers: listSuppliers(),
    presetPartId: url.searchParams.get('part_id') || ''
  };
}

export const actions = {
  default: async ({ request }) => {
    const form = await request.formData();
    const data = Object.fromEntries(form);

    const errors = {};
    if (!data.part_id)        errors.part_id  = 'movements.errors.part_required';
    const qty = Number(data.quantity);
    if (!Number.isInteger(qty) || qty < 0) errors.quantity = 'movements.errors.quantity_required';
    // 'in' or 'adjust' may legitimately use 0 (e.g. adjust to zero), so we
    // only block negative or non-integer; 'out' requires > 0.
    if (data.movement_type === 'out' && qty <= 0) errors.quantity = 'movements.errors.quantity_required';
    if (Object.keys(errors).length) return fail(400, { errors, values: data });

    try {
      recordMovement(data);
    } catch (err) {
      if (String(err.message).includes('not enough stock')) {
        return fail(400, { errors: { quantity: 'movements.errors.not_enough_stock' }, values: data });
      }
      throw err;
    }

    throw redirect(303, `/parts/${data.part_id}`);
  }
};
