using System.ComponentModel.DataAnnotations;
using Tiku.Application.QuestionBanks;
using Tiku.Domain.Content;

namespace Tiku.Api.Contracts;

/// <summary>
/// 题目题库查询参数。
/// </summary>
public sealed class QuestionBankQueryDto
{
    /// <summary>
    /// 租户编码。
    /// </summary>
    [StringLength(100)]
    public string? TenantCode { get; set; }

    /// <summary>
    /// 地区 ID。
    /// </summary>
    public Guid? RegionId { get; set; }

    /// <summary>
    /// 题库 ID。
    /// </summary>
    public Guid? QuestionBankId { get; set; }

    /// <summary>
    /// 科目 ID。
    /// </summary>
    public Guid? SubjectId { get; set; }

    /// <summary>
    /// 分类 ID。
    /// </summary>
    public Guid? CategoryId { get; set; }

    /// <summary>
    /// 节点 ID。
    /// </summary>
    public Guid? NodeId { get; set; }

    /// <summary>
    /// 内容入口 ID。
    /// </summary>
    public Guid? EntryId { get; set; }

    /// <summary>
    /// 内容节点 ID。
    /// </summary>
    public Guid? ContentNodeId { get; set; }

    /// <summary>
    /// 题集 ID。
    /// </summary>
    public Guid? CollectionId { get; set; }

    /// <summary>
    /// 来源。
    /// </summary>
    public QuestionSource? Source { get; set; }

    /// <summary>
    /// 类型。
    /// </summary>
    [StringLength(50)]
    public string? Type { get; set; }

    /// <summary>
    /// 关键字。
    /// </summary>
    [StringLength(100)]
    public string? Keyword { get; set; }

    /// <summary>
    /// 题目 ID 列表。
    /// </summary>
    public string? QuestionIds { get; set; }

    /// <summary>
    /// 返回数量上限。
    /// </summary>
    [Range(1, 500)]
    public int? Limit { get; set; }

    public QuestionBankFilter ToFilter(Guid tenantId, Guid? questionId = null)
    {
        return new QuestionBankFilter(
            tenantId,
            RegionId,
            QuestionBankId,
            SubjectId,
            CategoryId,
            NodeId,
            EntryId,
            ContentNodeId,
            CollectionId,
            questionId,
            ParseQuestionIds(),
            Type,
            Keyword,
            Limit,
            Source);
    }

    private Guid[] ParseQuestionIds()
    {
        if (string.IsNullOrWhiteSpace(QuestionIds))
        {
            return [];
        }

        return QuestionIds
            .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .Select(value => Guid.TryParse(value, out var id) ? id : (Guid?)null)
            .Where(id => id.HasValue)
            .Select(id => id!.Value)
            .Distinct()
            .Take(300)
            .ToArray();
    }
}
