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

namespace Tiku.Api.Contracts;

public sealed class QuestionBankQueryDto
{
    [StringLength(100)]
    public string? TenantCode { get; set; }

    public Guid? RegionId { get; set; }

    public Guid? QuestionBankId { get; set; }

    public Guid? SubjectId { get; set; }

    public Guid? CategoryId { get; set; }

    public Guid? NodeId { get; set; }

    public Guid? EntryId { get; set; }

    public Guid? ContentNodeId { get; set; }

    public Guid? CollectionId { get; set; }

    public QuestionSource? Source { get; set; }

    [StringLength(50)]
    public string? Type { get; set; }

    [StringLength(100)]
    public string? Keyword { get; set; }

    /// <summary>
    /// 题目 ID 列表，支持逗号分隔；最多取前 300 个。
    /// </summary>
    public string? QuestionIds { get; set; }

    [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();
    }
}
