using SQLite;
using Microsoft.Extensions.Logging;
using LSFE.MobApp.Entities.Location;
using LSFE.MobApp.Entities.Account;
using LSFE.MobApp.Entities.Doctor;
using LSFE.MobApp.Entities.Planning;
using LSFE.MobApp.Entities;

namespace LSFE.MobApp.Services
{
    public interface IDatabaseService
    {
        Task InitializeAsync();
        SQLiteAsyncConnection Database { get; }
    }
    public class DatabaseService : IDatabaseService
    {
        private SQLiteAsyncConnection _database;
        private readonly ILogger<DatabaseService> _logger;

        public DatabaseService(ILogger<DatabaseService> logger)
        {
            _logger = logger;
        }

        public SQLiteAsyncConnection Database => _database;

        public async Task InitializeAsync()
        {
            if (_database is not null)
                return;

            try
            {
                var databasePath = Path.Combine(FileSystem.AppDataDirectory, "LSFEApp.db3");//GetDatabasePath();//

                _database = new SQLiteAsyncConnection(databasePath);

                //await Delete(databasePath);

                // Create all tables based on your SQL schema
                await _database.CreateTableAsync<Entities.Doctor.Doctor>();
                await _database.CreateTableAsync<User>();
                await _database.CreateTableAsync<Institution>();
                await _database.CreateTableAsync<Attendance>();
                await _database.CreateTableAsync<Rating>();
                await _database.CreateTableAsync<Inventory>();
                await _database.CreateTableAsync<MobileInfo>();
                await _database.CreateTableAsync<Area>();
                await _database.CreateTableAsync<District>();
                await _database.CreateTableAsync<DSMScope>();
                await _database.CreateTableAsync<Territory>();
                await _database.CreateTableAsync<Division>();
                await _database.CreateTableAsync<MRPlanHeader>();
                await _database.CreateTableAsync<MRPlanDetail>();
                await _database.CreateTableAsync<Product>();
                await _database.CreateTableAsync<Cycle>();
                await _database.CreateTableAsync<MRRawPlan>();
                await _database.CreateTableAsync<InventoryTransaction>();
                await _database.CreateTableAsync<ProductTransaction>();
                await _database.CreateTableAsync<AddressCache>();

                // Apply any schema migrations
                // await MigrateDatabaseAsync();

                _logger.LogInformation("Database initialized successfully at {Path}", databasePath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error initializing database");
                throw;
            }
        }
        private async Task Delete(string path)
        {
            try
            {
                if (File.Exists(path))
                    File.Delete(path);

                await _database.CreateTableAsync<Entities.Doctor.Doctor>();
                await _database.CreateTableAsync<User>();
                await _database.CreateTableAsync<Institution>();
                await _database.CreateTableAsync<Attendance>();
                await _database.CreateTableAsync<Rating>();
                await _database.CreateTableAsync<Inventory>();
                await _database.CreateTableAsync<MobileInfo>();
                await _database.CreateTableAsync<Area>();
                await _database.CreateTableAsync<District>();
                await _database.CreateTableAsync<DSMScope>();
                await _database.CreateTableAsync<Territory>();
                await _database.CreateTableAsync<Division>();
                await _database.CreateTableAsync<MRPlanHeader>();
                await _database.CreateTableAsync<MRPlanDetail>();
                await _database.CreateTableAsync<Product>();
                await _database.CreateTableAsync<Cycle>();
                await _database.CreateTableAsync<MRRawPlan>();
                await _database.CreateTableAsync<InventoryTransaction>();
                await _database.CreateTableAsync<ProductTransaction>();
                _database = new SQLiteAsyncConnection(path);
            }
            catch (Exception ex)
            {
                ex.ToString();
                throw;
            }
        }
        private async Task MigrateDatabaseAsync()
        {
            try
            {
                // Check if tables exist and create them if missing
                var tableInfo = await _database.GetTableInfoAsync("ProductTransaction");
                if (tableInfo == null || !tableInfo.Any())
                {
                    _logger.LogInformation("Creating missing ProductTransaction table");
                    await _database.CreateTableAsync<ProductTransaction>();
                }

                tableInfo = await _database.GetTableInfoAsync("InventoryTransaction");
                if (tableInfo == null || !tableInfo.Any())
                {
                    _logger.LogInformation("Creating missing InventoryTransaction table");
                    await _database.CreateTableAsync<InventoryTransaction>();
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Error during migration - tables may already exist");
            }
        }
    }
}