using Microsoft.EntityFrameworkCore;
using FutureMailAPI.Data;
using FutureMailAPI.Models;
using FutureMailAPI.DTOs;
using System.Text.Json;

namespace FutureMailAPI.Services
{
    public interface IInitializationService
    {
        Task InitializeAsync();
    }
    
    public class InitializationService : IInitializationService
    {
        private readonly FutureMailDbContext _context;
        private readonly ILogger<InitializationService> _logger;
        
        public InitializationService(FutureMailDbContext context, ILogger<InitializationService> logger)
        {
            _context = context;
            _logger = logger;
        }
        
        public async Task InitializeAsync()
        {
            // 确保数据库已创建
            await _context.Database.EnsureCreatedAsync();
            
            // 创建默认OAuth客户端（如果不存在）
            await CreateDefaultOAuthClientAsync();
            
            _logger.LogInformation("系统初始化完成");
        }
        
        private async Task CreateDefaultOAuthClientAsync()
        {
            var defaultClientId = "futuremail_default_client";
            
            // 检查默认客户端是否已存在
            var existingClient = await _context.OAuthClients
                .FirstOrDefaultAsync(c => c.ClientId == defaultClientId);
                
            if (existingClient != null)
            {
                _logger.LogInformation("默认OAuth客户端已存在");
                return;
            }
            
            // 创建默认OAuth客户端
            var defaultClient = new Models.OAuthClient
            {
                ClientId = defaultClientId,
                ClientSecret = "futuremail_default_secret",
                Name = "FutureMail默认客户端",
                RedirectUris = JsonSerializer.Serialize(new[] { "http://localhost:3000/callback", "http://localhost:8080/callback" }),
                Scopes = JsonSerializer.Serialize(new[] { "read", "write" }),
                IsActive = true,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };
            
            _context.OAuthClients.Add(defaultClient);
            await _context.SaveChangesAsync();
            
            _logger.LogInformation("默认OAuth客户端创建成功");
        }
    }
}