import { fail } from '@sveltejs/kit';
import {
  listCategoriesWithCounts,
  createCategory,
  updateCategory,
  deleteCategory
} from '$lib/server/categories.js';

export function load() {
  return { categories: listCategoriesWithCounts() };
}

function validate(data) {
  const errors = {};
  if (!data.name_en?.trim() && !data.name_tg?.trim()) {
    errors.name = 'categories.errors.name_required';
  }
  const sort = Number(data.sort_order);
  if (data.sort_order !== '' && data.sort_order != null && !Number.isFinite(sort)) {
    errors.sort_order = 'categories.errors.sort_invalid';
  }
  return errors;
}

export const actions = {
  create: async ({ request }) => {
    const data = Object.fromEntries(await request.formData());
    const errors = validate(data);
    if (Object.keys(errors).length) return fail(400, { action: 'create', errors, values: data });
    createCategory(data);
    return { ok: true };
  },

  update: async ({ request }) => {
    const data = Object.fromEntries(await request.formData());
    const id = Number(data.id);
    if (!id) return fail(400, { errors: { id: 'categories.errors.id_missing' } });
    const errors = validate(data);
    if (Object.keys(errors).length) {
      return fail(400, { action: 'update', id, errors, values: data });
    }
    updateCategory(id, data);
    return { ok: true, updatedId: id };
  },

  delete: async ({ request }) => {
    const data = Object.fromEntries(await request.formData());
    const id = Number(data.id);
    if (id) deleteCategory(id);
    return { ok: true };
  }
};
