import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { Resend } from "resend";
import { db } from "@lila/db";
import * as schema from "@lila/db/schema";

const resend = new Resend(process.env["RESEND_API_KEY"]);
const emailFrom = process.env["EMAIL_FROM"] ?? "noreply@lilastudy.com";

export const auth = betterAuth({
  baseURL: process.env["BETTER_AUTH_URL"] || "http://localhost:3000",
  advanced: {
    cookiePrefix: "lila",
    defaultCookieAttributes: {
      ...(process.env["COOKIE_DOMAIN"] && {
        domain: process.env["COOKIE_DOMAIN"],
      }),
      secure: !!process.env["COOKIE_DOMAIN"],
      sameSite: "lax" as const,
    },
  },
  database: drizzleAdapter(db, { provider: "pg", schema }),
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
    sendResetPassword: async ({
      user,
      url,
    }: {
      user: { email: string };
      url: string;
    }) => {
      await resend.emails.send({
        from: emailFrom,
        to: user.email,
        subject: "Reset your lila password",
        html: `<p>Click <a href="${url}">here</a> to reset your password. This link expires in 1 hour.</p>`,
      });
    },
  },
  emailVerification: {
    sendOnSignUp: true,
    autoSignInAfterVerification: true,
    sendVerificationEmail: async ({
      user,
      url,
    }: {
      user: { email: string };
      url: string;
    }) => {
      await resend.emails.send({
        from: emailFrom,
        to: user.email,
        subject: "Verify your lila account",
        html: `<p>Click <a href="${url}">here</a> to verify your email address.</p>`,
      });
    },
  },
  trustedOrigins: [process.env["CORS_ORIGIN"] || "http://localhost:5173"],
  socialProviders: {
    google: {
      clientId: process.env["GOOGLE_CLIENT_ID"] as string,
      clientSecret: process.env["GOOGLE_CLIENT_SECRET"] as string,
    },
    github: {
      clientId: process.env["GITHUB_CLIENT_ID"] as string,
      clientSecret: process.env["GITHUB_CLIENT_SECRET"] as string,
    },
  },
});
