using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using e_suite.Database.Audit.Attributes;
using e_suite.Database.Core.Models;
using e_suite.Database.Core.Tables.CustomFields;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Database.Core.Tables.Glossaries;

[DisplayName("Glossary Custom Field Value")]
[Table("GlossaryCustomFieldValues", Schema = "Glossaries")]
[Index(nameof(GlossaryId), nameof(CustomFieldId), nameof(Index), IsUnique = true)]
[Index(nameof(Guid), IsUnique = true)]
public class GlossaryCustomFieldValue : IGeneralId, ICustomFieldValue
{
    [Key]
    public long Id { get; set; }

    [Required]
    public long GlossaryId { get; set; }

    [Required]
    public long CustomFieldId { get; set; }

    [Required]
    public long Index { get; set; }

    [Required]
    public string Value { get; set; } = string.Empty;

    [Required]
    public string DisplayValue { get; set; } = string.Empty;

    [Required]
    public Guid Guid { get; set; } = Guid.NewGuid();

    [AuditLastUpdated]
    public DateTimeOffset LastUpdated { get; set; }

    [AuditParent]
    [ForeignKey(nameof(GlossaryId))]
    public virtual Glossary Glossary { get; set; } = null!;

    [ForeignKey(nameof(CustomFieldId))]
    public virtual CustomField CustomField { get; set; } = null!;

    public static void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GlossaryCustomFieldValue>()
            .HasAlternateKey(gcfv => new { gcfv.GlossaryId, gcfv.CustomFieldId, gcfv.Index });

        modelBuilder.Entity<GlossaryCustomFieldValue>()
            .HasOne(gcfv => gcfv.Glossary)
            .WithMany(gcfv => gcfv.CustomFieldValues)
            .HasForeignKey(gcfv => gcfv.GlossaryId);
    }
}