import { C as error, O as fail, N as redirect } from '../../../../../chunks/utils.js-mIi_c4Oz.js';
import { a as hasRole, b as hashPassword } from '../../../../../chunks/auth.js-D502gejJ.js';
import { d as db } from '../../../../../chunks/db.js-le-jjQPv.js';
import { i as readUserForm, j as updateUser, k as getUser } from '../../../../../chunks/queries.js-BUUEc74j.js';

const load = async ({ params, locals }) => {
  if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
  const user = getUser(Number(params.id));
  if (!user) throw error(404, "Usuario no encontrado.");
  return { editUser: user };
};
const actions = {
  default: async ({ request, params, locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
    const id = Number(params.id);
    const form = await request.formData();
    const input = readUserForm(form);
    const password = String(form.get("password") ?? "");
    if (password && password.length < 8) {
      return fail(400, {
        error: "La contraseña debe tener al menos 8 caracteres.",
        values: Object.fromEntries(form)
      });
    }
    const res = updateUser(id, input, password ? hashPassword(password) : null);
    if (res.error) {
      return fail(400, { error: res.error, values: Object.fromEntries(form) });
    }
    throw redirect(303, "/users");
  },
  delete: async ({ params, locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
    const id = Number(params.id);
    if (id === locals.user.id) return fail(400, { error: "No puedes eliminar tu propia cuenta." });
    db.prepare("DELETE FROM users WHERE id = ?").run(id);
    throw redirect(303, "/users");
  }
};

var _page_server_ts = /*#__PURE__*/Object.freeze({
  __proto__: null,
  actions: actions,
  load: load
});

export { _page_server_ts as _ };
//# sourceMappingURL=_page.server.ts.js-ChayQFNG.js.map
