import { $Enums } from "@prisma/client";
import * as bcrypt from "bcrypt";
import { FastifyReply, FastifyRequest } from "fastify";
import prisma from "../../utils/prisma";
import { LoginSchema } from "./schema";

// ------------------------------------------------------------------------------------

export async function login(
  req: FastifyRequest<{
    Body: LoginSchema;
  }>,
  reply: FastifyReply
) {
  const { email, password } = req.body;

  const user = await prisma.user.findUnique({
    where: { email: email },
    include: { company: true },
  });
  const isMatch = user && (await bcrypt.compare(password, user.password));

  if (
    !user ||
    !isMatch ||
    !user.active ||
    (user.company && !user.company.active)
  ) {
    return reply.code(401).send({
      message: "Aucun compte actif trouvé avec ces informations",
    });
  }

  if (user.role === $Enums.Role.User) {
    return reply.code(401).send({
      message: "Vous n'êtes pas un admin",
    });
  }

  const payload = {
    id: user.id,
    email: user.email,
    role: user.role,
    permissions: user.permissions,
  };

  const token = req.jwt.sign(payload, { expiresIn: "1d" });
  return reply.code(200).send({ access: token });
}
