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 Microsoft.EntityFrameworkCore;

namespace e_suite.Database.Core.Tables.Domain;

[DisplayName("Role")]
[Table("Roles", Schema = "Domain")]
[Index(nameof(Guid), IsUnique = true)]
[Index(nameof(DomainId), nameof(Name), IsUnique = true)]
public class Role : IGeneralId, ISoftDeletable
{
    [Key]
    public long Id { get; set; }

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

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

    /// <summary>
    /// Super users are automatically allows to do anything on any domain
    /// </summary>
    [Required]
    public bool IsSuperUser { get; set; } = false;

    /// <summary>
    /// Administrators are automatically allowed to do anything on the Domain specified by DomainId
    /// </summary>
    [Required]
    public bool IsAdministrator { get; set; } = false;

    [Required]
    public bool CanDelete { get; set; } = true;

    [Required]
    [DefaultValue(1)]
    public long DomainId { get; set; }

    [AuditSoftDelete(true)]
    [Required]
    [DefaultValue(false)]
    public bool Deleted { get; set; } = false;

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

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

    public virtual ICollection<UserRole> UserRoles { get; set; } = new List<UserRole>();

    public static void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Role>().HasData(new Role
        {
            Id = 1,
            Guid = new Guid("{32D65817-4DE4-4BD5-912E-2B33054A2171}"),
            Name = "Super Users",
            IsSuperUser = true,
            IsAdministrator = false,
            CanDelete = false,
            DomainId = 1,
            Deleted = false,
        });

        modelBuilder.Entity<Role>().HasData(new Role
        {
            Id = 2,
            Guid = new Guid("{2F77F57C-FE2C-4A36-AD17-5D902AFC86CB}"),
            Name = "Administrators",
            IsSuperUser = false,
            IsAdministrator = true,
            CanDelete = false,
            DomainId = 1,
            Deleted = false,
        });

        modelBuilder.Entity<Role>()
            .HasMany(r => r.UserRoles)
            .WithOne(ur => ur.Role)
            .HasForeignKey(ur => ur.RoleId);
    }
}