using Microsoft.Extensions.Logging;
using Database.Models;

namespace Database.Services
{
    public interface IDatabaseSeeder
    {
        Task SeedAsync();
        Task SeedUsersAsync();
        Task SeedProvidersAsync();
        Task SeedTestDataAsync();
    }
    
    public class DatabaseSeeder : IDatabaseSeeder
    {
        private readonly DatabaseContext _context;
        private readonly IPasswordHasher _passwordHasher;
        private readonly ILogger<DatabaseSeeder> _logger;
        
        public DatabaseSeeder(DatabaseContext context, IPasswordHasher passwordHasher, ILogger<DatabaseSeeder> logger)
        {
            _context = context;
            _passwordHasher = passwordHasher;
            _logger = logger;
        }
        
        public async Task SeedAsync()
        {
            try
            {
                _logger.LogInformation("Starting database seeding...");
                
                await SeedUsersAsync();
                await SeedProvidersAsync();
                
                await _context.SaveChangesAsync();
                
                _logger.LogInformation("Database seeding completed successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Database seeding failed");
                throw;
            }
        }
        
        public async Task SeedUsersAsync()
        {
            if (!_context.Users.Any())
            {
                _logger.LogInformation("Seeding default users...");
                
                var adminUser = new User
                {
                    Username = "admin",
                    PasswordHash = _passwordHasher.HashPassword("admin123"),
                    Role = "Admin",
                    Email = "admin@company.com",
                    FirstName = "System",
                    LastName = "Administrator",
                    IsActive = true,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                var testUser = new User
                {
                    Username = "user",
                    PasswordHash = _passwordHasher.HashPassword("user123"),
                    Role = "User",
                    Email = "user@company.com",
                    FirstName = "Test",
                    LastName = "User",
                    IsActive = true,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                var readOnlyUser = new User
                {
                    Username = "readonly",
                    PasswordHash = _passwordHasher.HashPassword("readonly123"),
                    Role = "ReadOnly",
                    Email = "readonly@company.com",
                    FirstName = "ReadOnly",
                    LastName = "User",
                    IsActive = true,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                _context.Users.AddRange(adminUser, testUser, readOnlyUser);
                
                _logger.LogInformation("Added {Count} default users", 3);
            }
        }
        
        public async Task SeedProvidersAsync()
        {
            await SeedStorageProvidersAsync();
            await SeedHelpCenterProvidersAsync();
        }
        
        private async Task SeedStorageProvidersAsync()
        {
            if (!_context.StorageProviders.Any())
            {
                _logger.LogInformation("Seeding default storage providers...");
                
                var s3Provider = new StorageProvider
                {
                    Name = "AWS S3",
                    Type = "S3",
                    Description = "Amazon Web Services S3 Storage",
                    IsActive = true,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                s3Provider.SetConfiguration(new StorageProviderConfiguration
                {
                    Region = "us-east-2",
                    Bucket = "software-releases",
                    CloudFrontDomain = "https://cdn.company.com/",
                    AdditionalSettings = new Dictionary<string, object>
                    {
                        ["EnableCDN"] = true,
                        ["EnableVersioning"] = true,
                        ["DefaultExpiration"] = 365
                    }
                });
                
                var boxProvider = new StorageProvider
                {
                    Name = "Box.com",
                    Type = "Box",
                    Description = "Box.com Cloud Storage",
                    IsActive = false,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                boxProvider.SetConfiguration(new StorageProviderConfiguration
                {
                    Container = "software-releases",
                    AdditionalSettings = new Dictionary<string, object>
                    {
                        ["EnableSharedLinks"] = true,
                        ["DefaultPermission"] = "view"
                    }
                });
                
                var ftpProvider = new StorageProvider
                {
                    Name = "FTP Server",
                    Type = "FTP",
                    Description = "Legacy FTP Server",
                    IsActive = false,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                ftpProvider.SetConfiguration(new StorageProviderConfiguration
                {
                    Host = "ftp.company.com",
                    Port = 21,
                    UseSSL = false,
                    AdditionalSettings = new Dictionary<string, object>
                    {
                        ["PassiveMode"] = true,
                        ["BinaryMode"] = true
                    }
                });
                
                _context.StorageProviders.AddRange(s3Provider, boxProvider, ftpProvider);
                
                _logger.LogInformation("Added {Count} storage providers", 3);
            }
        }
        
        private async Task SeedHelpCenterProvidersAsync()
        {
            if (!_context.HelpCenterProviders.Any())
            {
                _logger.LogInformation("Seeding default help center providers...");
                
                var zendeskProvider = new HelpCenterProvider
                {
                    Name = "Zendesk",
                    Type = "Zendesk",
                    Description = "Zendesk Help Center Integration",
                    IsActive = true,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                zendeskProvider.SetConfiguration(new HelpCenterProviderConfiguration
                {
                    Subdomain = "company",
                    ApiVersion = "v2",
                    DefaultLocale = "en-us",
                    DefaultTemplateVariables = new Dictionary<string, string>
                    {
                        ["VERSION"] = "{{VERSION}}",
                        ["SWURL"] = "{{SWURL}}",
                        ["PDFURL"] = "{{PDFURL}}",
                        ["DATE"] = "{{DATE}}",
                        ["PROJECT"] = "{{PROJECT}}"
                    }
                });
                
                var salesforceProvider = new HelpCenterProvider
                {
                    Name = "Salesforce Service",
                    Type = "Salesforce",
                    Description = "Salesforce Service Cloud Integration",
                    IsActive = false,
                    CreatedBy = "System",
                    CreatedAt = DateTime.UtcNow
                };
                
                salesforceProvider.SetConfiguration(new HelpCenterProviderConfiguration
                {
                    LoginUrl = "https://login.salesforce.com",
                    ApiVersion = "v58.0",
                    DefaultLocale = "en-us"
                });
                
                _context.HelpCenterProviders.AddRange(zendeskProvider, salesforceProvider);
                
                _logger.LogInformation("Added {Count} help center providers", 2);
            }
        }
        
        public async Task SeedTestDataAsync()
        {
            _logger.LogInformation("Seeding test data...");
            
            await SeedTestProjectsAsync();
            await SeedTestPackagesAsync();
            
            await _context.SaveChangesAsync();
            
            _logger.LogInformation("Test data seeding completed");
        }
        
        private async Task SeedTestProjectsAsync()
        {
            if (!_context.Projects.Any())
            {
                var projects = new[]
                {
                    new Project
                    {
                        Name = "DataPRO LTS",
                        Description = "Long Term Support version of DataPRO",
                        CCNetProjectName = "DATAPRO_MAINT_4_00",
                        Status = "Active",
                        CreatedBy = "System",
                        CreatedAt = DateTime.UtcNow
                    },
                    new Project
                    {
                        Name = "DataPRO Stable",
                        Description = "Stable release version of DataPRO", 
                        CCNetProjectName = "DATAPRO_MAINT_4_04",
                        Status = "Active",
                        CreatedBy = "System",
                        CreatedAt = DateTime.UtcNow
                    }
                };
                
                _context.Projects.AddRange(projects);
            }
        }
        
        private async Task SeedTestPackagesAsync()
        {
            if (!_context.Packages.Any() && _context.Projects.Any())
            {
                var ltsProject = _context.Projects.First(p => p.CCNetProjectName == "DATAPRO_MAINT_4_00");
                var stableProject = _context.Projects.First(p => p.CCNetProjectName == "DATAPRO_MAINT_4_04");
                
                var packages = new[]
                {
                    new Package
                    {
                        Title = "DataPRO LTS Release",
                        Version = "4.0.1205",
                        Description = "Long term support release for enterprise customers",
                        ProjectId = ltsProject.Id,
                        Status = "Draft",
                        CreatedBy = "System",
                        CreatedAt = DateTime.UtcNow
                    },
                    new Package
                    {
                        Title = "DataPRO Stable Release",
                        Version = "4.4.305",
                        Description = "Latest stable release with new features",
                        ProjectId = stableProject.Id,
                        Status = "Draft",
                        CreatedBy = "System",
                        CreatedAt = DateTime.UtcNow
                    }
                };
                
                _context.Packages.AddRange(packages);
            }
        }
    }
}