using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json;

namespace Database.Models
{
    public class Publication : BaseEntity
    {
        public int PackageId { get; set; }
        
        [Required]
        [MaxLength(50)]
        public string Status { get; set; } = "Pending"; // Pending, InProgress, Completed, Failed, Cancelled
        
        public DateTime? PublishedAt { get; set; }
        
        public string? ReleaseNotesPath { get; set; }
        
        // JSON column for PostgreSQL
        [Column(TypeName = "jsonb")]
        public string? PublicationDetails { get; set; }
        
        public string? ErrorMessage { get; set; }
        
        public TimeSpan? Duration => PublishedAt?.Subtract(CreatedAt);
        
        // Navigation properties
        [ForeignKey(nameof(PackageId))]
        public Package Package { get; set; } = null!;
        
        public ICollection<PublishingStep> Steps { get; set; } = new List<PublishingStep>();
        
        // Helper methods for PublicationDetails JSON
        public PublicationDetailsModel GetPublicationDetails()
        {
            if (string.IsNullOrEmpty(PublicationDetails))
                return new PublicationDetailsModel();
                
            try
            {
                return JsonSerializer.Deserialize<PublicationDetailsModel>(PublicationDetails) ?? new PublicationDetailsModel();
            }
            catch
            {
                return new PublicationDetailsModel();
            }
        }
        
        public void SetPublicationDetails(PublicationDetailsModel details)
        {
            PublicationDetails = JsonSerializer.Serialize(details);
        }
        
        // Helper properties
        public bool IsCompleted => Status == "Completed" && PublishedAt.HasValue;
        
        public bool IsFailed => Status == "Failed";
        
        public bool IsInProgress => Status == "InProgress";
        
        public int ProgressPercentage => Steps.Any() ? 
            (int)(Steps.Count(s => s.Status == "Completed") * 100.0 / Steps.Count) : 0;
    }
    
    public class PublicationDetailsModel
    {
        public string? BuildVersion { get; set; }
        public string? ReleaseNotesUrl { get; set; }
        public string? PackageUrl { get; set; }
        public string? CDNUrl { get; set; }
        public List<string> UploadedFiles { get; set; } = new();
        public List<string> UpdatedArticles { get; set; } = new();
        public Dictionary<string, object> AdditionalDetails { get; set; } = new();
    }
}