import { count } from "drizzle-orm";
import { database } from "@/db";
import { user } from "@/db/schema/auth";
import { libraryFolders } from "@/db/schema/libraries";
import { auth } from "@/lib/auth";
import type {
	AccountData,
	LibraryData,
	MetadataLanguage,
	OnboardConfigurationData,
	OnboardStepType,
} from "@/models";
import { BaseService } from "../BaseService";
import { LibraryScannerService } from "../libraryScanner/LibraryScanner";

export interface OnboardContext {
	currentStep: OnboardStepType;
	account?: AccountData;
	libraries: LibraryData[];
	language?: MetadataLanguage;
	completed: boolean;
}

export class OnboardService extends BaseService {
	public isRunning = false;
	private needsOnboarding = false;

	constructor() {
		super("OnboardService");
	}

	private get libraryScannerService() {
		return this.services.get(LibraryScannerService);
	}

	public async mount(): Promise<void> {
		this.logger.info("Mounting onboard service.");

		// Check if onboarding is needed by querying user count
		await this.checkOnboardingNeeded();

		this.isRunning = true;
	}

	public async dispose(): Promise<void> {
		this.logger.info("Disposing onboard service.");
		this.isRunning = false;
	}

	private async checkOnboardingNeeded(): Promise<void> {
		try {
			const userCountResult = await database
				.select({ count: count() })
				.from(user);

			const userCount = userCountResult[0]?.count || 0;
			this.needsOnboarding = userCount === 0;

			this.logger.info(
				`Onboarding check: ${userCount} users found. Needs onboarding: ${this.needsOnboarding}`,
			);
		} catch (error) {
			this.logger.error("Failed to check onboarding status:", error);
			// Default to needing onboarding if database check fails
			this.needsOnboarding = true;
		}
	}

	public getNeedsOnboarding(): boolean {
		return this.needsOnboarding;
	}

	public async completeOnboarding(
		body: OnboardConfigurationData,
	): Promise<void> {
		try {
			// Create user account
			await auth.api.createUser({
				body: {
					email: body.account.email,
					name: body.account.name,
					password: body.account.password,
					role: "admin",
				},
			});
			// Save libraries with language settings
			if (body.libraries && body.libraries.length > 0) {
				const librariesToInsert = body.libraries.map((library) => ({
					name: library.name,
					type: library.type,
					path: library.path,
					primaryLanguage: body.languages.primary,
					fallbackLanguage: body.languages.fallback,
				}));

				await database.insert(libraryFolders).values(librariesToInsert);
				this.logger.info(`Inserted ${librariesToInsert.length} libraries`);

				// Trigger library scan after inserting libraries
				this.logger.info("Triggering library scan after onboarding...");
				this.libraryScannerService.scanFolder();
			}

			// After completing onboarding, refresh the needsOnboarding status
			this.needsOnboarding = false;
			this.logger.info("Onboarding completed successfully");
		} catch (error) {
			this.logger.error("Failed to complete onboarding:", error);
			throw error;
		}
	}
}
