import Google from '@auth/core/providers/google';
import { defineConfig } from 'auth-astro';

/**
 * Usar `process.env` para runtime en Vercel; `import.meta.env` como respaldo si Vite lo inlinó en build.
 */
function authSecret(): string | undefined {
  const fromProcess = process.env.AUTH_SECRET;
  if (typeof fromProcess === 'string' && fromProcess.trim().length > 0) {
    return fromProcess.trim();
  }
  const fromMeta = import.meta.env.AUTH_SECRET;
  if (typeof fromMeta === 'string' && fromMeta.trim().length > 0) {
    return fromMeta.trim();
  }
  return undefined;
}

function allowedEmails(): string[] {
  const raw = process.env.AUTH_ALLOWED_EMAILS ?? import.meta.env.AUTH_ALLOWED_EMAILS;
  if (typeof raw === 'string' && raw.trim()) {
    return raw
      .split(',')
      .map((e) => e.trim().toLowerCase())
      .filter(Boolean);
  }
  return ['inadaptadocl@gmail.com', 'nico.gaitangomez@gmail.com'];
}

export default defineConfig({
  trustHost: true,
  secret: authSecret(),
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          prompt: 'select_account',
        },
      },
    }),
  ],
  callbacks: {
    async signIn({ user }) {
      const email = user?.email?.toLowerCase();
      if (!email) return false;
      return allowedEmails().includes(email);
    },
  },
});
