using BookReader.Services;

namespace BookReader;

public partial class App : Application
{
    private readonly IDatabaseService _databaseService;
    private bool _isInitialized;

    public App(IDatabaseService databaseService)
    {
        InitializeComponent();
        _databaseService = databaseService;
    }

    protected override Window CreateWindow(IActivationState? activationState)
    {
        return new Window(new AppShell());
    }

    protected override async void OnStart()
    {
        base.OnStart();
        await InitializeDatabaseAsync(CancellationToken.None);
    }

    protected override async void OnResume()
    {
        base.OnResume();
        await InitializeDatabaseAsync(CancellationToken.None);
    }

    private async Task InitializeDatabaseAsync(CancellationToken ct = default)
    {
        if (_isInitialized) return;

        try
        {
            await _databaseService.InitializeAsync(ct);
            _isInitialized = true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"[App] Database initialization error: {ex.Message}");
        }
    }
}