import { db } from "@/db";
import * as schema from "@/db/schema";
import { sendMagicLinkEmail } from "@/lib/mail";
import { ac, adminRole, userRole } from "@/lib/permissions";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, magicLink } from "better-auth/plugins";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
    schema: {
      user: schema.user,
      session: schema.session,
      account: schema.account,
      verification: schema.verification,
    },
  }),
  plugins: [
    admin({
      defaultRole: "user",
      adminRoles: ["admin"],
      ac,
      roles: {
        admin: adminRole,
        user: userRole,
      },
    }),
    magicLink({
      sendMagicLink: async ({ email, url }) => {
        await sendMagicLinkEmail(email, url);
      },
      expiresIn: 60 * 5, // 5 分钟过期
    }),
  ],
  rateLimit: {
    enabled: true,
    storage: "memory",
    rules: {
      // magic link 发送限制：每 5 秒最多 5 次
      magicLink: { limit: 5, window: 5 },
    },
  },
});

export type Session = typeof auth.$Infer.Session;
