import NextAuth, { AuthOptions } from "next-auth";
import CredentialProvider from "next-auth/providers/credentials";
import { sha256sum } from "@/lib/util";
import { validateCredentials } from "@/lib/db";
import { GRAVATAR_DEFAULT } from "@/lib/constants";
import { auditLogRaw } from "@/lib/audit";

const authOptions: AuthOptions = {
  providers: [
    CredentialProvider({
      name: 'Mail account',
      credentials: {
        email: { label: "E-Mail", type: "email", placeholder: "webmistress@amogus.cloud" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        console.log(`[${credentials?.email}] Authentication attempt`);

        if (credentials && await validateCredentials(credentials.email, credentials.password)) {
          console.log(`[${credentials.email}] Authentication succeeded`);

          const emailHash = sha256sum(credentials.email.trim().toLowerCase());

          await auditLogRaw({
            user: credentials.email,
            ts: new Date().toISOString(),
            action: "login",
          });

          return {
            id: credentials.email,
            email: credentials.email,
            image: `https://gravatar.com/avatar/${emailHash}?d=${GRAVATAR_DEFAULT}`,
          };
        }

        console.log(`[${credentials?.email}] Authentication failed`);
        return null;
      },
    }),
  ],
  session: {
    strategy: 'jwt',
    maxAge: 4 * 60 * 60 // 4 hours
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
