using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
using Tiku.Api.Contracts;
using Tiku.Application.Jobs;
using Tiku.Domain.Catalog;
using Tiku.Domain.Common;
using Tiku.Domain.Content;
using Tiku.Domain.Identity;
using Tiku.Domain.Operations;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Persistence;

namespace Tiku.IntegrationTests.Api;

public sealed class DirectContentEndpointTests
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
    {
        Converters = { new JsonStringEnumConverter() }
    };

    [Fact]
    public async Task Tenant_admin_can_create_question_and_sync_primary_collection()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        var collectionId = Guid.NewGuid();
        await factory.SeedAsync(new QuestionCollection
        {
            Id = collectionId,
            TenantId = seed.TenantId,
            Name = "直接迁移题集",
            CollectionType = QuestionCollectionType.Manual,
            SourceType = QuestionCollectionSourceType.ManualQuestions
        });
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        using var response = await client.PostAsJsonAsync(
            "/api/tenant/content/questions",
            new DirectQuestionWriteDto
            {
                PrimaryCollectionId = collectionId,
                Type = "choice",
                Content = "1 + 1 = ?",
                Options = JsonSerializer.SerializeToElement(new[] { "1", "2" }),
                CorrectOptionIndex = 1,
                Tags = JsonSerializer.SerializeToElement(new[] { "math" })
            });
        var json = await ReadJsonAsync(response);
        var questionId = json.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal(collectionId, json.RootElement.GetProperty("item").GetProperty("primaryCollectionId").GetGuid());

        using var scope = factory.CreateSystemScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
        Assert.Contains(dbContext.QuestionCollectionItems,
            item => item.CollectionId == collectionId && item.QuestionId == questionId);
        Assert.Equal(1, dbContext.QuestionCollections.Single(item => item.Id == collectionId).QuestionCount);
    }

    [Fact]
    public async Task Published_objective_question_requires_authoritative_answer_but_draft_does_not()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        using var published = await client.PostAsJsonAsync(
            "/api/tenant/content/questions",
            new DirectQuestionWriteDto { Type = "choice", Content = "缺少答案", Status = "Published" });
        using var draft = await client.PostAsJsonAsync(
            "/api/tenant/content/questions",
            new DirectQuestionWriteDto { Type = "choice", Content = "草稿题", Status = "Draft" });

        Assert.Equal(HttpStatusCode.BadRequest, published.StatusCode);
        Assert.Equal("question_grading_rule_invalid", await ReadProblemCodeAsync(published));
        Assert.Equal(HttpStatusCode.OK, draft.StatusCode);
    }

    [Fact]
    public async Task Tenant_admin_can_upsert_vocabulary_handbook_video_and_operations_content()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        var unitResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/vocabulary-units",
            new DirectVocabularyUnitDto { Name = "Unit 1", WordCount = 1 });
        var unitJson = await ReadJsonAsync(unitResponse);
        var unitId = unitJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        var wordResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/vocabulary-words",
            new DirectVocabularyWordDto { UnitId = unitId, Word = "scale", Meaning = "规模" });

        var subjectResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/handbook-subjects",
            new DirectHandbookSubjectDto { Name = "文化常识", Type = "Common" });
        var subjectJson = await ReadJsonAsync(subjectResponse);
        var subjectId = subjectJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        var chapterResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/handbook-chapters",
            new DirectHandbookChapterDto { SubjectId = subjectId, Name = "第一章" });
        var chapterJson = await ReadJsonAsync(chapterResponse);
        var chapterId = chapterJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        var entryResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/handbook-entries",
            new DirectHandbookEntryDto { ChapterId = chapterId, Title = "知识点", Content = "正文" });

        var videoResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/videos",
            new DirectVideoDto { Title = "解析视频", VideoUrl = "https://example.test/video.mp4" });

        var bannerResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/operations/banners",
            new DirectOperationContentDto { Title = "开屏", Content = "欢迎", IsActive = true });
        using var bannerListResponse = await client.GetAsync("/api/tenant/content/operations/banners");
        var bannerListJson = await ReadJsonAsync(bannerListResponse);

        Assert.Equal(HttpStatusCode.OK, unitResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, wordResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, subjectResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, chapterResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, entryResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, videoResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, bannerResponse.StatusCode);
        Assert.Single(bannerListJson.RootElement.GetProperty("items").EnumerateArray());
    }

    [Fact]
    public async Task Tenant_admin_can_bind_question_video_and_run_import_skeleton()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        var questionResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/questions",
            new DirectQuestionWriteDto { Type = "choice", Content = "题目", CorrectOptionIndex = 0 });
        var questionJson = await ReadJsonAsync(questionResponse);
        var questionId = questionJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        var videoResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/videos",
            new DirectVideoDto { Title = "视频" });
        var videoJson = await ReadJsonAsync(videoResponse);
        var videoId = videoJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();

        var bindResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/question-videos",
            new DirectQuestionVideoDto { QuestionId = questionId, VideoId = videoId });

        var previewResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/imports/preview/questions",
            new DirectImportDto
            {
                Items =
                [
                    JsonSerializer.SerializeToElement(
                        new { type = "choice", content = "导入预览题", correctOptionIndex = 0 })
                ]
            });
        var previewJson = await ReadJsonAsync(previewResponse);
        var previewJobId = previewJson.RootElement.GetProperty("job").GetProperty("id").GetGuid();

        var executeResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/imports/questions",
            new DirectImportDto
            {
                Items =
                [
                    JsonSerializer.SerializeToElement(
                        new { type = "choice", content = "导入执行题", correctOptionIndex = 0 })
                ]
            });
        var executeJson = await ReadJsonAsync(executeResponse);
        var executeJobId = executeJson.RootElement.GetProperty("job").GetProperty("id").GetGuid();

        var postCheckResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/imports/post-check",
            new DirectImportJobDto { JobId = executeJobId });

        Assert.Equal(HttpStatusCode.OK, bindResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, previewResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, executeResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, postCheckResponse.StatusCode);
        Assert.NotEqual(Guid.Empty, previewJobId);

        using var scope = factory.CreateSystemScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
        Assert.True(dbContext.ContentImportJobs.Any(item => item.Id == executeJobId && item.InsertedCount == 1));
        Assert.True(dbContext.Questions.Count(item => item.TenantId == seed.TenantId) >= 2);
        Assert.True(dbContext.Questions.Single(item => item.Id == questionId).HasVideoExplanation);
    }

    [Fact]
    public async Task Tenant_admin_can_queue_content_import_and_worker_writes_import_detail()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        var queueResponse = await client.PostAsJsonAsync(
            "/api/tenant/content/imports/questions",
            new DirectImportDto
            {
                Async = true,
                Items =
                [
                    JsonSerializer.SerializeToElement(
                        new { type = "choice", content = "异步导入题", correctOptionIndex = 0 })
                ]
            });
        var queuedJob = await queueResponse.Content.ReadFromJsonAsync<BackgroundJobItem>(JsonOptions);

        using var scope = factory.CreateSystemScope();
        var jobService = scope.ServiceProvider.GetRequiredService<IBackgroundJobService>();
        var processed = await jobService.ProcessPendingAsync("content-import-test-worker", 10);
        var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
        var storedJob = dbContext.BackgroundJobs.Single(item => item.Id == queuedJob!.Id);
        var importJobId = storedJob.Result.GetProperty("importJobId").GetGuid();

        var detailResponse = await client.GetAsync($"/api/tenant/content/imports/detail?jobId={importJobId}");
        var detail = await ReadJsonAsync(detailResponse);

        Assert.Equal(HttpStatusCode.Accepted, queueResponse.StatusCode);
        Assert.Equal(1, processed);
        Assert.Equal(BackgroundJobStatus.Succeeded, storedJob.Status);
        Assert.Equal(HttpStatusCode.OK, detailResponse.StatusCode);
        Assert.Equal(1, detail.RootElement.GetProperty("job").GetProperty("insertedCount").GetInt32());
        Assert.Single(detail.RootElement.GetProperty("items").EnumerateArray());
    }

    [Fact]
    public async Task Tenant_admin_can_upsert_scoreline_fields_and_records()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        var regionId = Guid.NewGuid();
        var schoolId = Guid.NewGuid();
        var majorId = Guid.NewGuid();
        await factory.SeedAsync(
            new Region { Id = regionId, TenantId = seed.TenantId, Name = "四川" },
            new School { Id = schoolId, TenantId = seed.TenantId, RegionId = regionId, Name = "美术学院" },
            new Major
            {
                Id = majorId, TenantId = seed.TenantId, RegionId = regionId, SchoolId = schoolId, Name = "视觉传达"
            });
        using var client = factory.CreateClient();
        await LoginAsync(client, seed);

        var fieldResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/scoreline/fields",
            new DirectScorelineFieldDto
            {
                RegionId = regionId,
                FieldKey = "cultureScore",
                FieldName = "文化分",
                FieldType = "number",
                IsFilter = true,
                IsTrend = true
            });
        var recordResponse = await client.PutAsJsonAsync(
            "/api/tenant/content/scoreline/records",
            new DirectScorelineRecordDto
            {
                RegionId = regionId,
                SchoolId = schoolId,
                MajorId = majorId,
                Year = 2026,
                SchoolName = "美术学院",
                MajorName = "视觉传达",
                FieldValues = JsonSerializer.SerializeToElement(new { cultureScore = 420, rank = "A" })
            });

        var fieldsResponse = await client.GetAsync($"/api/tenant/content/scoreline/fields?regionId={regionId}");
        var recordsResponse =
            await client.GetAsync($"/api/tenant/content/scoreline/records?regionId={regionId}&year=2026");
        var fieldsJson = await ReadJsonAsync(fieldsResponse);
        var recordsJson = await ReadJsonAsync(recordsResponse);

        Assert.Equal(HttpStatusCode.OK, fieldResponse.StatusCode);
        Assert.Equal(HttpStatusCode.OK, recordResponse.StatusCode);
        Assert.Single(fieldsJson.RootElement.GetProperty("items").EnumerateArray());
        Assert.Single(recordsJson.RootElement.GetProperty("items").EnumerateArray());
    }

    [Fact]
    public async Task RegionBackedDirectContent_UsesRestrictedScopeAndReturns404ForOutsideWrite()
    {
        await using var factory = new ApiTestFactory();
        var seed = await SeedAdminAsync(factory);
        var allowedRegionId = Guid.NewGuid();
        var outsideRegionId = Guid.NewGuid();
        var allowedSchool = new School
        {
            TenantId = seed.TenantId,
            RegionId = allowedRegionId,
            Name = "Allowed School"
        };
        var outsideSchool = new School
        {
            TenantId = seed.TenantId,
            RegionId = outsideRegionId,
            Name = "Outside School"
        };
        await factory.SeedAsync(
            new Region { Id = allowedRegionId, TenantId = seed.TenantId, Name = "Allowed Region" },
            new Region { Id = outsideRegionId, TenantId = seed.TenantId, Name = "Outside Region" },
            allowedSchool,
            outsideSchool);
        await SetDataScopeAsync(factory, seed.TenantId, new
        {
            mode = "restricted",
            regionIds = new[] { allowedRegionId },
            includesSelf = false
        });

        using var client = factory.CreateClient();
        await LoginAsync(client, seed);
        using var listResponse = await client.GetAsync("/api/tenant/content/scoreline/schools");
        using var list = await ReadJsonAsync(listResponse);
        using var deniedUpdate = await client.PutAsJsonAsync(
            "/api/tenant/content/scoreline/schools",
            new DirectSchoolDto
            {
                Id = outsideSchool.Id,
                RegionId = outsideRegionId,
                Name = "Hidden Update"
            });

        Assert.Equal([allowedSchool.Id], list.RootElement.GetProperty("items").EnumerateArray()
            .Select(item => item.GetProperty("id").GetGuid()));
        Assert.Equal(HttpStatusCode.NotFound, deniedUpdate.StatusCode);
    }

    private static async Task<(Guid TenantId, Guid UserId, string Phone)> SeedAdminAsync(ApiTestFactory factory)
    {
        var tenantId = Guid.NewGuid();
        var userId = Guid.NewGuid();
        var phone = $"137{Random.Shared.Next(10000000, 99999999)}";
        await factory.SeedAsync(
            new Tenant
            {
                Id = tenantId,
                Slug = tenantId.ToString("N"),
                Name = "Test Tenant",
                Status = TenantStatus.Active,
                Metadata = JsonDefaults.Object()
            },
            new User
            {
                Id = userId,
                Phone = phone,
                Name = "Tenant Admin"
            }.WithTestPassword(),
            new TenantMembership
            {
                TenantId = tenantId,
                UserId = userId,
                Role = TenantRole.TenantAdmin,
                Status = MembershipStatus.Active
            });

        return (tenantId, userId, phone);
    }

    private static async Task LoginAsync(
        HttpClient client,
        (Guid TenantId, Guid UserId, string Phone) seed)
    {
        client.UseAccessToken(await client.LoginAsTenantAsync(seed.TenantId, seed.Phone));
    }

    private static async Task SetDataScopeAsync(ApiTestFactory factory, Guid tenantId, object value)
    {
        using var scope = factory.CreateSystemScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
        var role = dbContext.TenantBackendRoles.Single(item =>
            item.TenantId == tenantId && item.Code == "integration_test_admin");
        role.DataScope = JsonSerializer.SerializeToElement(value);
        await dbContext.SaveChangesAsync();
    }

    private static async Task<JsonDocument> ReadJsonAsync(HttpResponseMessage response)
    {
        var stream = await response.Content.ReadAsStreamAsync();
        return await JsonDocument.ParseAsync(stream);
    }

    private static async Task<string?> ReadProblemCodeAsync(HttpResponseMessage response)
    {
        using var payload = await ReadJsonAsync(response);
        return payload.RootElement.TryGetProperty("code", out var code) ? code.GetString() : null;
    }
}