using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using e_suite.Database.Audit;
using e_suite.Service.SigmaImporter.Extensions;
using eSuite.Core.Miscellaneous;

namespace e_suite.Service.SigmaImporter.PrintSpecifications;

public partial class PrintSpecificationImporter
{
    public readonly Guid PrintSpecificationFormGuid  = new("e84d8a56-b025-44b9-80b3-bf9324644e23");
    public readonly Guid GeneralPrintSpecificationGlossaryItemGuid = new("ef1be548-ec7f-4c16-b2fe-d8f89b5ead54");
    public readonly Guid PrintSpecificationCustomFieldGuid = new("8D910089-3079-4A29-ABAD-8DDF82DB6DBB");

    private async Task<GetFormTemplate> MakeSurePrintSpecCustomFormCreated(AuditUserDetails auditUserDetails)
    {
        GeneralIdRef printSpecificationFormRefId = PrintSpecificationFormGuid.ToGeneralIdRef();
        GetFormTemplate printSpecificationFormTemplate;
        try
        {
            printSpecificationFormTemplate =
                await _formsManager.GetFormTemplateAsync(printSpecificationFormRefId, CancellationToken.None);
        }
        catch (NotFoundException)
        {
            var createFormTemplate = new CreateFormTemplate
            {
                Guid = PrintSpecificationFormGuid,
                Name = "General Print Specification",
                Definition = GetDefinitionFromFile()
            };
            await _formsManager.CreateFormTemplateAsync(auditUserDetails, createFormTemplate, CancellationToken.None);
            printSpecificationFormTemplate =
                await _formsManager.GetFormTemplateAsync(printSpecificationFormRefId, CancellationToken.None);

            var glossary = new NewGlossaryItem
            {
                Parent = _importGlossaryHelper.PrintSpecificationGlossaryGeneralIdRef,
                Guid = GeneralPrintSpecificationGlossaryItemGuid,
                Name = createFormTemplate.Name,
                CustomFieldValues =
                [
                    new CustomFieldValues
                    {
                        Id = PrintSpecificationCustomFieldGuid.ToGeneralIdRef(),
                        Values =
                        [
                            new CustomFieldValue
                            {
                                DisplayValue = printSpecificationFormTemplate.Name,
                                Value = printSpecificationFormTemplate.Guid.ToGeneralIdRef().ToJson()
                            }
                        ]
                    }
                ]
            };

            await _importGlossaryHelper.EnsureGlossaryItemExists(auditUserDetails, glossary);
        }

        return printSpecificationFormTemplate;
    }

    private string GetDefinitionFromFile()
    {
        var generalPrintSpecificationFormTemplateDefinition = File.ReadAllText("Resources/GeneralPrintSpecificationFormTemplateDefintion.txt");
        return generalPrintSpecificationFormTemplateDefinition;
    }
}