import { User } from '@typings-ce';
import { inject, injectable } from 'inversify';
import { MEET_ADMIN_SECRET, MEET_ADMIN_USER } from '../environment.js';
import { PasswordHelper } from '../helpers/index.js';
import { LoggerService, MeetStorageService, UserService } from './index.js';

@injectable()
export class AuthService {
	constructor(
		@inject(LoggerService) protected logger: LoggerService,
		@inject(UserService) protected userService: UserService,
		@inject(MeetStorageService) protected globalPrefService: MeetStorageService
	) {}

	async authenticate(username: string, password: string): Promise<User | null> {
		const isAdmin = this.authenticateAdmin(username, password);
		const isUser = await this.authenticateUser(username, password);

		if (isAdmin || isUser) {
			return this.userService.getUser(username);
		}

		return null;
	}

	private authenticateAdmin(username: string, password: string): boolean {
		return username === MEET_ADMIN_USER && password === MEET_ADMIN_SECRET;
	}

	private async authenticateUser(username: string, password: string): Promise<boolean> {
		const userCredentials = await this.userService.getStoredUserCredentials();

		if (!userCredentials) {
			return false;
		}

		const isPasswordValid = await PasswordHelper.verifyPassword(password, userCredentials.passwordHash);
		return username === userCredentials.username && isPasswordValid;
	}
}
