import { fail } from '@sveltejs/kit';
import { listSuppliers, createSupplier, deleteSupplier } from '$lib/server/suppliers.js';

export function load() {
  return { suppliers: listSuppliers() };
}

export const actions = {
  create: async ({ request }) => {
    const form = await request.formData();
    const data = Object.fromEntries(form);
    if (!data.name || !data.name.trim()) {
      return fail(400, { errors: { name: 'suppliers.errors.name_required' }, values: data });
    }
    createSupplier(data);
    return { ok: true };
  },
  delete: async ({ request }) => {
    const form = await request.formData();
    const id = Number(form.get('id'));
    if (id) deleteSupplier(id);
    return { ok: true };
  }
};
