import fastifySession from '@fastify/session'
import fp from 'fastify-plugin'
import { Auth } from '../../schemas/auth.js'
import fastifyCookie from '@fastify/cookie'

declare module 'fastify' {
  interface Session {
    user: Auth
  }
}

/**
 * This plugins enables the use of session.
 *
 * @see {@link https://github.com/fastify/session}
 */
export default fp(async (fastify) => {
  // Get cookie secret from config or use a default for development
  const cookieSecret = fastify.config?.COOKIE_SECRET || process.env.COOKIE_SECRET || 'development-secret-for-session-do-not-use-in-production'
  
  if (!cookieSecret) {
    fastify.log.warn('No COOKIE_SECRET found in config or environment. Using an insecure default secret. DO NOT USE IN PRODUCTION!')
  } else if (cookieSecret === 'development-secret-for-session-do-not-use-in-production') {
    fastify.log.warn('Using the default insecure cookie secret. DO NOT USE IN PRODUCTION!')
  }
  
  // Get cookie name from config or use a default
  const cookieName = fastify.config?.COOKIE_NAME || process.env.COOKIE_NAME || 'web3proxy'
  
  // Get cookie secure setting or default to false for development
  const cookieSecured = fastify.config?.COOKIE_SECURED !== undefined 
    ? fastify.config.COOKIE_SECURED 
    : (process.env.COOKIE_SECURED === 'true' || false)

  fastify.register(fastifyCookie)
  fastify.register(fastifySession, {
    secret: cookieSecret,
    cookieName: cookieName,
    cookie: {
      secure: cookieSecured,
      httpOnly: true,
      maxAge: 1800000 // 30 minutes
    }
  })
}, {
  name: 'session',
  dependencies: ['env-config'] // Make sure env-config runs first
})
