import { db } from "@/server/db";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { admin, openAPI } from "better-auth/plugins";

type MailSender = (args: {
  to: string;
  subject: string;
  html: string;
}) => Promise<void>;

export function createAuthInstance(options?: {
  sendMail?: MailSender;
  disableEmail?: boolean;
}) {
  const mailDisabled = options?.disableEmail ?? false;
  const sendMail =
    options?.sendMail ??
    (async ({ to, subject }: { to: string; subject: string }) => {
      const message = `sendMail no está configurado. Se omitió el envío de correo a ${to} con asunto "${subject}".`;
      if (mailDisabled) {
        console.debug(message);
      } else {
        console.warn(message);
      }
    });

  return betterAuth({
    database: drizzleAdapter(db, {
      provider: "pg",
    }),

    plugins: [openAPI(), admin(), nextCookies()], // nextCookies() debe ir al final
    session: {
      expiresIn: 60 * 60 * 24 * 7, // 7 días
      updateAge: 60 * 60 * 24, // refresco diario
      cookieCache: {
        enabled: true,
        maxAge: 5 * 60,
      },
    },
    user: {
      additionalFields: {
        role: {
          type: "string",
          default: "user",
          required: false,
          defaultValue: "user",
        },
      },
      changeEmail: {
        enabled: true,
        sendChangeEmailVerification: async ({ newEmail, url }) => {
          await sendMail({
            to: newEmail,
            subject: "Verify your email change",
            html: `<p>Click the link to verify: ${url}</p>`,
          });
        },
      },
    },

    emailAndPassword: {
      enabled: true,
      requireEmailVerification: false,
      sendResetPassword: async ({ user, url }) => {
        await sendMail({
          to: user.email,
          subject: "Reset your password",
          html: `<p>Click the link to reset your password: ${url}</p>`,
        });
      },
    },
    disabledPaths: ["/sign-up/email", "/sign-up/social/github"],
  });
}
