using FitConnect.Services.Models;
using FitConnect.Services.Models.v1;

namespace FitConnect.Models;

public class Submission {
    public string? Id { get; set; }
    public string? CaseId { get; set; }
    public Destination? Destination { get; set; } = new();

    public string DestinationId {
        get => Destination.DestinationId;
        set => Destination.DestinationId = value;
    }

    public List<Attachment> Attachments { get; set; } = new();

    public ServiceType? ServiceType { get; set; }

    public Callback? Callback { get; set; }
    public Metadata? Metadata { get; set; }
    public Data? Data { get; set; }
    public string? EncryptedMetadata { get; set; }
    public string? EncryptedData { get; set; }

    public bool IsSubmissionReadyToAdd(out string? error) {
        var innerError = "";
        if (string.IsNullOrEmpty(DestinationId)) innerError += "DestinationId is required\r\n";

        if (ServiceType.IsValid()) innerError += "ServiceType is invalid\r\n";

        if (string.IsNullOrWhiteSpace(innerError)) {
            error = null;
            return true;
        }

        error = innerError.Trim();
        return false;
    }

    public bool IsSubmissionReadyToSend() {
        return true;
    }

    public static explicit operator Submission(SubmissionForPickupDto dto) {
        return new Submission {
            Id = dto.SubmissionId,
            Callback = null,
            DestinationId = dto.DestinationId,
            ServiceType = null
        };
    }

    public static explicit operator Submission(SubmissionDto dto) {
        return new Submission {
            Id = dto.SubmissionId,
            Callback = (Callback)dto.Callback,
            DestinationId = dto.DestinationId,
            ServiceType = (ServiceType)dto.ServiceType,
            EncryptedData = dto.EncryptedData,
            EncryptedMetadata = dto.EncryptedMetadata
        };
    }

    public static explicit operator SubmitSubmissionDto(Submission dto) {
        return new() {
            EncryptedData = dto.EncryptedData,
            EncryptedMetadata = dto.EncryptedMetadata
        };
    }

    public static explicit operator CreateSubmissionDto(Submission sub) {
        var result = new CreateSubmissionDto {
            AnnouncedAttachments = sub.Attachments.Select(a => a.Id).ToList(),
            DestinationId = sub.DestinationId
        };
        if (sub.ServiceType != null)
            result.ServiceType = (ServiceTypeDto)sub.ServiceType;
        if (sub.Callback != null) result.Callback = (CallbackDto)sub.Callback;

        return result;
    }
}