using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(setupAction =>
{
    setupAction.EnableAnnotations();
    setupAction.SchemaFilter<SwaggerSchemaExampleFilter>();
});

var app = builder.Build();

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

app.UseHttpsRedirection();

var group = app.MapGroup("/").DisableAntiforgery().WithTags("PADP Reference API");
var pocGroup = app.MapGroup("/poc").DisableAntiforgery().WithTags("Encrypt/decrypt POC");

UserProperties userProperties = app.Configuration.GetSection("UserProperties").Get<UserProperties>();

ApimHelper apimHelper = new ApimHelper(userProperties);

group.MapGet("/idp/b2b-access-token", () => 
{
    return apimHelper.GetB2bAccessToken();
})
.Produces<B2bAccessToken>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GetB2bAccessToken")
.WithSummary("API 1020 - Get B2B Access Token")
.WithDescription("Returns a client access token, needed for most other PADP APIs.")
.WithOpenApi();

group.MapGet("/get-image-from-base64", ([FromHeader]string base64String) => 
{
    return apimHelper.GetImageFromBase64(base64String);
})
.Produces<FileContentHttpResult>(200, "image/jpeg")
.WithName("GetImageFromBase64")
.WithSummary("Get rendered image from Base64 encoded String")
.WithOpenApi();

group.MapPost("/personal-data/{xtat}", (string xTat, [SwaggerParameter("Email address to be used for OTP challenges")] string email, [SwaggerParameter("Should be at least two words (first name and last name)")] string? name, [SwaggerParameter("Should be a date between 1900-01-01 and now, in the format YYYY-MM-DD")] string? birthDate, [SwaggerSchema("Should be a JPG image, of max. 512KB and resolution between 520x520 and 720x720")] IFormFile? photo) =>
{
    Console.WriteLine("Creating personal data for xTAT: " + xTat);
    return apimHelper.CreatePersonalData(xTat, email, name, birthDate, photo);
})
.Produces(201)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("CreatePersonalData")
.WithSummary("API 1201 - Create Personal Data - First create an ephemeral key using API 1210!")
.WithDescription("First create an ephemeral key using API 1210!")
.WithOpenApi();

group.MapPost("/personal-data/{xtat}/with-email-verification", (string xTat, [SwaggerParameter("Email address to be used for OTP challenges")]string email, [SwaggerParameter("This user access token will be used for e-mail verification if provided - otherwise, the internally stored one (based on previous V3 1206+1207 calls) will be used")]string? userAccessToken, [SwaggerParameter("Should be at least two words (first name and last name)")]string? name, [SwaggerParameter("Should be a date between 1900-01-01 and now, in the format YYYY-MM-DD")]string? birthDate, [SwaggerSchema("Should be a JPG image, of max. 512KB and resolution between 520x520 and 720x720")]IFormFile? photo) => 
{
    Console.WriteLine("Creating personal data with e-mail verification for xTAT: " + xTat);
    return apimHelper.CreatePersonalDataWithEmailVerification(xTat, email, userAccessToken,name, birthDate, photo);
})
.Produces(201)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("CreatePersonalDataWithEmailVerification")
.WithSummary("API 1201 - Create Personal Data with e-mail verification - First create an ephemeral key using API 1210!")
.WithDescription("Performs extra e-mail verification using OTP flow; using internally stored (after 1206+1207 call) or explicitly provided user access token. First create an ephemeral key using API 1210!")
.WithOpenApi();

group.MapGet("/personal-data/{xtat}", (string xTat, [SwaggerParameter("If provided, this user access token will be used over the internally stored one (that was restrieved via earlier 1206+1207 calls)")]string? userAccessToken) => 
{
    Console.WriteLine("Retrieving personal data for xTAT: " + xTat);
    return apimHelper.GetPersonalData(xTat, userAccessToken);
})
.Produces<PersonalData>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GetPersonalData")
.WithSummary("API 1202 - Get Personal Data - First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithDescription("First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithOpenApi();

group.MapGet("/personal-data/{xtat}/decrypted", (string xTat, [SwaggerParameter("If provided, this user access token will be used over the internally stored one (that was restrieved via earlier 1206+1207 calls)")]string? userAccessToken) => 
{
    Console.WriteLine("Retrieving decrypted personal data for xTAT: " + xTat);
    return apimHelper.GetDecryptedPersonalData(xTat, userAccessToken);
})
.Produces<DecryptedPersonalData>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GetDecryptedPersonalData")
.WithSummary("API 1202 - Get Personal Data AND decrypt response - First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithDescription("First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithOpenApi();

group.MapDelete("/personal-data/{xtat}", (string xTat, [SwaggerParameter("If provided, this user access token will be used over the internally stored one (that was restrieved via earlier 1206+1207 calls)")]string? userAccessToken) => 
{
    Console.WriteLine("Deleting personal data for xTAT: " + xTat);
    return apimHelper.DeletePersonalData(xTat, userAccessToken);
})
.Produces<DeletePersonalDataResponse>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("DeletePersonalData")
.WithSummary("API 1204 - Delete Personal Data - First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithDescription("First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithOpenApi();

group.MapPut("/personal-data/{xtat}", (string xTat, [SwaggerParameter("If provided, this user access token will be used over the internally stored one (that was restrieved via earlier 1206+1207 calls)")]string? userAccessToken, bool skipUpdateCounter, [SwaggerParameter("Should be at least two words (first name and last name)")]string? name, [SwaggerParameter("Should be a date between 1900-01-01 and now, in the format YYYY-MM-DD")]string? birthDate, [SwaggerSchema("Should be a JPG image, of max. 512KB and resolution between 520x520 and 720x720")]IFormFile? photo) => 
{
    Console.WriteLine("Replacing personal data for xTAT: " + xTat);
    return apimHelper.UpdatePersonalData(xTat, userAccessToken, skipUpdateCounter, name, birthDate, photo);
})
.WithName("UpdatePersonalData")
.WithSummary("API 1205 - Update Personal Data - First perform an OTP challenge using API 1206 and 1207 or explicitly provide user access token!")
.WithDescription("Performs a complete replacement; empty request parameters will result in the corresponding PADP attribute being deleted.")
.WithOpenApi();

group.MapGet("/v2/personal-data/{xtat}/generate-otp", (string xTat) => 
{
    Console.WriteLine("Generating OTP for xTAT: " + xTat);
    return apimHelper.GenerateOtpV2(xTat);
})
.Produces<OtpResponse>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GenerateOtpV2")
.WithSummary("API 1206 V2 - Generate OTP")
.WithOpenApi();

group.MapGet("/v2/personal-data/{xtat}/validate-otp", (string xTat, string otp) =>
{
    Console.WriteLine("Validating OTP {0} for xTAT: {1}", otp, xTat);
    return apimHelper.ValidateOtpV2(xTat, otp);
})
.Produces<UserAccessToken>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("ValidateOtpV2")
.WithSummary("API 1207 V2 - Validate OTP")
.WithOpenApi();

group.MapGet("/v3/personal-data/generate-otp", (string? email, string? xTat) => 
{
    if (email != null){
        Console.WriteLine("Generating OTP for e-mail: " + email);
    } else if (xTat != null){
        Console.WriteLine("Generating OTP for xTAT: " + xTat);
    }
    return apimHelper.GenerateOtpV3(email, xTat);
})
.Produces<OtpResponse>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GenerateOtpV3")
.WithSummary("API 1206 V3 - Generate OTP")
.WithDescription("If e-mail is provided, the OTP is generated for the e-mail address. If xTAT is provided, the OTP is generated for the xTAT.")
.WithOpenApi();

group.MapGet("/v3/personal-data/validate-otp", (string? email, string? xTat, string otp) => 
{
    if (email != null){
        Console.WriteLine("Validating OTP {0} for e-mail: {1}", otp, email);
    } else if (xTat != null){
        Console.WriteLine("Validating OTP {0} for xTAT: {1}", otp, xTat);
    }
    return apimHelper.ValidateOtpV3(email, xTat, otp);
})
.Produces<UserAccessToken>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("ValidateOtpV3")
.WithSummary("API 1207 V3 - Validate OTP")
.WithDescription("If e-mail is provided, the OTP is validated for the e-mail address. If xTAT is provided, the OTP is validated for the xTAT.")
.WithOpenApi();

group.MapGet("/personal-data/{xtat}/encrypted-update-init", (string xTat) => 
{
    return apimHelper.CreateEphemeralKey(xTat);
})
.Produces<EphemeralKey>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("CreateEphemeralKey")
.WithSummary("API 1210 - Create Ephemeral Key")
.WithOpenApi();

group.MapGet("/personal-data/{xtat}/administrative-data", (string xTat) => 
{
    Console.WriteLine("Retrieving administrative data for xTAT: {0}", xTat);
    return apimHelper.GetAdministrativeData(xTat);
})
.Produces<AdministrativeData>(200)
.Produces<ErrorResponse>(400)
.Produces<ErrorResponse>(404)
.Produces<ErrorResponse>(500)
.WithName("GetAdministrativeData")
.WithSummary("API 1211 - Get Administrative Data")
.WithOpenApi();

pocGroup.MapGet("/encrypt-decrypt-poc", ([FromHeader]string textToEncrypt, string encryptedEphemeralKey) => 
{
    Console.WriteLine("Text to encrypt: {0}", textToEncrypt);
    return apimHelper.EncryptDecryptPoc(textToEncrypt, encryptedEphemeralKey);
})
.WithName("EncryptDecryptPoc")
.WithSummary("Encrypt/Decrypt POC")
.WithOpenApi();

pocGroup.MapGet("/encrypt-poc", ([FromHeader]string textToEncrypt, string encryptedEphemeralKey) => 
{
    Console.WriteLine("Text to encrypt: {0}", textToEncrypt);
    return apimHelper.EncryptPoc(textToEncrypt, encryptedEphemeralKey);
})
.WithName("EncryptPoc")
.WithSummary("Encrypt POC")
.WithOpenApi();

pocGroup.MapGet("/decrypt-poc", ([FromHeader]string textToDecrypt, string encryptedEphemeralKey) => 
{
    Console.WriteLine("Text to decrypt: {0}", textToDecrypt);
    return apimHelper.DecryptPoc(textToDecrypt, encryptedEphemeralKey);
})
.WithName("DecryptPoc")
.WithSummary("Decrypt POC")
.WithOpenApi();

app.Run();
