using Microsoft.EntityFrameworkCore;
using TodoTask = TodoList.Core.Entities.Task;

namespace TodoList.Api.Data;

/// <summary>
/// 待办事项数据库上下文类，用于 Entity Framework Core 数据访问
/// </summary>
public class TodoDbContext : DbContext
{
    /// <summary>
    /// 构造函数，初始化数据库上下文
    /// </summary>
    /// <param name="options">数据库上下文选项</param>
    public TodoDbContext(DbContextOptions<TodoDbContext> options) : base(options)
    {
    }

    /// <summary>
    /// 任务数据集
    /// </summary>
    public DbSet<TodoTask> Tasks { get; set; }

    /// <summary>
    /// 配置模型关系和约束
    /// </summary>
    /// <param name="modelBuilder">模型构建器</param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<TodoTask>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Title).IsRequired().HasMaxLength(200);
            entity.Property(e => e.Priority).HasDefaultValue(TodoList.Core.Entities.TaskPriority.Medium);
            entity.Property(e => e.IsCompleted).HasDefaultValue(false);
            entity.Property(e => e.CreatedAt).HasDefaultValueSql("datetime('now')");
            entity.Property(e => e.UpdatedAt).HasDefaultValueSql("datetime('now')");

            entity.HasOne(e => e.ParentTask)
                .WithMany(e => e.SubTasks)
                .HasForeignKey(e => e.ParentTaskId)
                .OnDelete(DeleteBehavior.Restrict);
        });
    }
}
