using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Solar.Api.Converters;
using Solar.Api.Services;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Text.Json;

namespace Solar.Api;

public partial class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Services
        builder.Services.AddScoped<SolarService>();
        builder.Services.AddMemoryCache();

        // Database
        builder.Services.AddDbContext<DatabaseContext>(options =>
        {
            options.UseSqlite(builder.Configuration.GetConnectionString("Database"));
        });

        // REST infrastructure
        builder.Services.AddCors(options =>
        {
            options.AddPolicy(
                name: "default",
                policy =>
                {
                    policy.WithOrigins("http://localhost:8080");
                });
        });

        builder.Services.AddControllers().AddJsonOptions(config =>
        {
            config.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            config.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            config.JsonSerializerOptions.Converters.Add(new DateOnlyConverter());
            config.JsonSerializerOptions.Converters.Add(new TimeOnlyConverter());
        });
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen(config =>
        {
            config.MapType<DateOnly>(() => new OpenApiSchema
            {
                Type = "string",
                Format = "date",
                Example = OpenApiAnyFactory.CreateFromJson("\"2022-12-31\"")
            });
            config.MapType<TimeOnly>(() => new OpenApiSchema
            {
                Type = "string",
                Format = "time",
                Example = OpenApiAnyFactory.CreateFromJson("\"13:45:42.0000000\"")
            });

            config.SupportNonNullableReferenceTypes();
            config.EnableAnnotations();
        });

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseHttpsRedirection();
            app.UseSwagger();
            app.UseSwaggerUI();
            app.UseCors("default");
        }

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}
