import { Inject, Injectable } from '@nestjs/common'
import { FastifyRequest } from 'fastify'
import { AuthModuleOptions, AuthStrategy, OPTIONS_KEY } from '../types'

/**
 * Validates credentials against Google Booking Server configuration.
 */
@Injectable()
export class GoogleBookingServerAuthStrategy implements AuthStrategy {
	constructor(@Inject(OPTIONS_KEY) readonly options: AuthModuleOptions) {}

	async validate(request: FastifyRequest): Promise<unknown> {
		const credentials = this.extractCredentials(request)
		if (!credentials) return null

		if (!credentials.username || !credentials.password) return null

		if (
			credentials.username !== this.options.googleBookingServer.username ||
			credentials.password !== this.options.googleBookingServer.password
		) {
			return null
		}

		const user = { username: credentials.username }
		;(request as any)['user'] = user

		return user
	}

	private extractCredentials(request: FastifyRequest): { username: string; password: string } | null {
		const authHeader = request.headers.authorization

		if (!authHeader || !authHeader.startsWith('Basic ')) {
			return null
		}

		try {
			const base64Credentials = authHeader.slice(6)
			const credentials = Buffer.from(base64Credentials, 'base64').toString('utf8')
			const [username, password] = credentials.split(':')
			return { username, password }
		} catch {
			return null
		}
	}
}
