import fp from 'fastify-plugin'

declare module 'fastify' {
  interface FastifyRequest {
    locationId: string
    user: { id: string; role: string }
  }
}

/**
 * Dev-only auth bypass. Used when JWT_SECRET is not set in development.
 * NEVER runs in production — main.ts guards against this.
 */
export const devAuthPlugin = fp(async (app) => {
  if (process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test') {
    throw new Error('Dev auth plugin cannot be used outside development/test environments')
  }

  app.addHook('onRequest', async (request) => {
    const locationId =
      (request.headers['x-location-id'] as string) ?? '00000000-0000-0000-0000-000000000010'
    const userId =
      (request.headers['x-user-id'] as string) ?? '00000000-0000-0000-0000-000000000001'

    request.locationId = locationId
    request.user = {
      id: userId,
      role: 'admin',
    }
  })

  // No-op decorators so routes that use authenticate/requireRole still work
  app.decorate('authenticate', async function () {})
  app.decorate('requireRole', function () {
    return async function () {}
  })
})

declare module 'fastify' {
  interface FastifyInstance {
    authenticate: (request: any, reply: any) => Promise<void>
    requireRole: (...roles: string[]) => (request: any, reply: any) => Promise<void>
  }
}
