import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { genericOAuth } from "better-auth/plugins";
import type { PrismaClient } from "@prisma/client";

export function createAuth(prisma: PrismaClient) {
  return betterAuth({
    database: prismaAdapter(prisma, {
      provider: "postgresql",
    }),
    emailAndPassword: {
      enabled: true, // Enable for now, can be disabled later
    },
    plugins: [
      genericOAuth({
        config: [
          {
            providerId: "authentik",
            clientId: process.env.OIDC_CLIENT_ID ?? "",
            clientSecret: process.env.OIDC_CLIENT_SECRET ?? "",
            discoveryUrl: `${process.env.OIDC_ISSUER ?? ""}.well-known/openid-configuration`,
            scopes: ["openid", "profile", "email"],
          },
        ],
      }),
    ],
    session: {
      expiresIn: 60 * 60 * 24, // 24 hours
      updateAge: 60 * 60 * 24, // 24 hours
    },
    trustedOrigins: [
      process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
      "http://localhost:3001", // API origin (dev)
      "https://app.mosaicstack.dev", // Production web
      "https://api.mosaicstack.dev", // Production API
    ],
  });
}

export type Auth = ReturnType<typeof createAuth>;
