using QYZH.InteractiveMagazine.Infrastructure.RabbitMQ;
using QYZH.InteractiveMagazine.Infrastructure.Redis;
using QYZH.InteractiveMagazine.Infrastructure.SDK;
using QYZH.InteractiveMagazine.PrintWorker.Consumers;
using Serilog;
using SqlSugar;
using SqlSugar.IOC;
using System.Text;
using Yitter.IdGenerator;

Directory.SetCurrentDirectory(AppContext.BaseDirectory);

var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings
{
    Args = args,
    ContentRootPath = AppContext.BaseDirectory
});
const string serviceName = "QYZH.InteractiveMagazine.PrintWorker";

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);

var logDirectory = Path.Combine(AppContext.BaseDirectory, "logs");
Directory.CreateDirectory(logDirectory);
var logFilePath = Path.Combine(logDirectory, "printworker-log-.txt");

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day, encoding: Encoding.UTF8)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Services.AddSerilog();
builder.Services.AddWindowsService(options => options.ServiceName = serviceName);

YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = 3 });

builder.Services.AddSqlSugar(new IocConfig
{
    ConfigId = 0,
    DbType = IocDbType.MySql,
    ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"),
    IsAutoCloseConnection = true
});

SugarIocServices.ConfigurationSugar(db =>
{
    db.Aop.OnLogExecuting = (sql, pars) =>
    {
        Log.Information("[SQL] {Sql}", UtilMethods.GetSqlString((DbType)IocDbType.MySql, sql, pars));
    };
    db.Aop.OnError = ex =>
    {
        Log.Error(ex, "[SQL Error] {Message}", ex.Message);
    };
});

builder.Services.AddScoped<ISqlSugarClient>(_ => DbScoped.SugarScope);
builder.Services.AddCSRedisCacheExtension(builder.Configuration.GetSection("RedisSettings"));
builder.Services.AddHttpClient();
builder.Services.AddSDKService(builder.Configuration);
builder.Services.AddRabbitMQ(builder.Configuration);

builder.Services.AddScoped<IQueueConsumer, AutoDotCodeConsumer>();
builder.Services.AddHostedService<RabbitMQHostedService>();

var app = builder.Build();

Log.Information("{ServiceName} 已启动，仅消费自动铺码队列", serviceName);

await app.RunAsync();
