import { z } from 'zod';
import { d as defineEventHandler, u as useLogger, r as readValidatedBody, U as User, c as createError } from '../../nitro/nitro.mjs';
import bcrypt from 'bcryptjs';
import { s as setSession } from '../../_/session.mjs';
import 'luxon';
import '@sequelize/core';
import 'html-to-text';
import 'crypto';
import 'node:fs';
import 'sharp';
import 'path';
import 'node:stream';
import 'jsdom';
import 'dompurify';
import 'mime-types';
import 'fs';
import 'fs/promises';
import 'linkify-html';
import '@peertube/http-signature';
import 'jsonld';
import 'lodash.intersection';
import 'email-templates';
import 'node:http';
import 'node:https';
import 'node:crypto';
import 'node:events';
import 'node:buffer';
import 'node:path';
import 'vue';
import 'vue-router';
import 'dotenv';
import 'url';
import 'slugify';
import 'umzug';
import 'consola';
import '@sequelize/core/decorators-legacy';
import 'util';
import 'mitt';
import 'ical.js';
import 'node:url';
import 'fast-xml-parser';
import '../../_/getUser.mjs';
import '../../_/jwt.mjs';
import 'jose';

const bodySchema = z.object({
  email: z.string(),
  // TODO: .email(), // or admin
  password: z.string()
});
const index_post = defineEventHandler(async (event) => {
  const log = useLogger("login");
  const { email, password } = await readValidatedBody(event, bodySchema.parse);
  log.info(`Login ${email}`);
  const user = await User.withScope("withPassword").findOne({ where: { email, is_active: true } });
  if (!user || !password) {
    log.warn("E-mail not found or not active", email);
    throw createError({ status: 401, message: "Bad credentials" });
  }
  if (await bcrypt.compare(password, user.password)) {
    await setSession(event, {
      user: {
        id: user.id,
        email: user.email,
        role: user.role
      }
    });
    log.info("Logged in ", user.email);
    return { email: user.email, role: user.role };
  } else {
    log.error("Bad credentials for ", user.email);
    throw createError({ statusCode: 401, message: "Bad credentials" });
  }
});

export { index_post as default };
