import 'server-only'

import { cookies } from 'next/headers'
import { createClient } from '@supabase/supabase-js'

const STORAGE_KEY = 'hha-google-oauth'
const GOOGLE_CONTEXT_COOKIE = 'hha_google_context_'

export function googleContextCookie(flowId: string): string | null {
  return /^[a-f0-9]{32}$/.test(flowId) ? `${GOOGLE_CONTEXT_COOKIE}${flowId}` : null
}

export interface GoogleContext {
  mode: 'login' | 'signup'
  role: 'broker' | 'dispatcher' | 'driver'
  company: string
  next: string | null
}

export function googleAuthConfigured(): boolean {
  return !!(
    process.env.NEXT_PUBLIC_SUPABASE_URL &&
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY &&
    process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY &&
    process.env.RECAPTCHA_SECRET_KEY
  )
}

export function safeNextPath(value: string | null | undefined): string | null {
  if (!value || !value.startsWith('/') || value.startsWith('//') || value.includes('\\') || /[\u0000-\u001f]/.test(value)) return null
  return value
}

/**
 * Supabase PKCE needs a verifier across the Google redirect. Only verifier
 * keys are persisted in short-lived HttpOnly cookies; Supabase access and
 * refresh tokens are intentionally never stored in browser cookies here.
 * The app issues its own session after the code is exchanged.
 */
export async function createGoogleOAuthClient() {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL
  const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY
  if (!url || !key) throw new Error('Supabase Google Auth is not configured.')
  const jar = await cookies()
  const isVerifierKey = (name: string) => name.startsWith(STORAGE_KEY) && name.endsWith('-code-verifier')
  return createClient(url, key, {
    auth: {
      flowType: 'pkce',
      autoRefreshToken: false,
      detectSessionInUrl: false,
      persistSession: true,
      storageKey: STORAGE_KEY,
      experimental: { appendPkceFlowIdToRedirects: true },
      storage: {
        getItem: (name) => isVerifierKey(name) ? jar.get(name)?.value ?? null : null,
        setItem: (name, value) => {
          if (isVerifierKey(name)) jar.set(name, value, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 600 })
        },
        removeItem: (name) => { if (isVerifierKey(name)) jar.delete(name) },
      },
    },
  })
}
