import { betterAuth } from "better-auth"
import { prismaAdapter } from "better-auth/adapters/prisma"
import { customSession } from "better-auth/plugins"

import { env } from "./env"
import { prisma } from "./prisma"

export const auth = betterAuth({
  secret: env.BETTER_AUTH_SECRET,
  baseURL: env.BETTER_AUTH_URL,
  // Permite login tanto no domínio de produção quanto no localhost em DEV
  trustedOrigins: Array.from(
    new Set(
      [
        env.BETTER_AUTH_URL,
        env.NEXT_PUBLIC_APP_URL,
        process.env.NODE_ENV !== "production" ? "http://localhost:3000" : undefined,
        process.env.NODE_ENV !== "production" ? "http://127.0.0.1:3000" : undefined,
      ].filter(Boolean) as string[]
    )
  ),
  database: prismaAdapter(prisma, {
    provider: "sqlite",
  }),
  user: {
    modelName: "authUser",
    additionalFields: {
      role: {
        type: "string",
        required: false,
        defaultValue: "agent",
        input: false,
      },
      tenantId: {
        type: "string",
        required: false,
      },
      avatarUrl: {
        type: "string",
        required: false,
      },
      machinePersona: {
        type: "string",
        required: false,
        input: false,
      },
    },
  },
  session: {
    modelName: "authSession",
    cookieCache: {
      enabled: true,
      maxAge: 60 * 5,
    },
  },
  account: {
    modelName: "authAccount",
  },
  verification: {
    modelName: "authVerification",
  },
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: false,
  },
  plugins: [
    customSession(async ({ user, session }) => {
      const expiresAt = session.expiresAt instanceof Date
        ? session.expiresAt.getTime()
        : new Date(session.expiresAt ?? Date.now()).getTime()

      return {
        session: {
          id: session.id,
          expiresAt,
        },
        user: {
          id: user.id,
          name: user.name,
          email: user.email,
          role: ((user as { role?: string }).role ?? "agent").toLowerCase(),
          tenantId: (user as { tenantId?: string | null }).tenantId ?? null,
          avatarUrl: (user as { avatarUrl?: string | null }).avatarUrl ?? null,
          machinePersona: (user as { machinePersona?: string | null }).machinePersona ?? null,
        },
      }
    }),
  ],
})

export type AppAuth = typeof auth
