using System.Security.Claims;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;

namespace JobTrackerApi.Tests;

public sealed class JobApplicationsMariaDraftTests
{
    [Fact]
    public async Task Save_application_drafts_can_store_recruiter_message()
    {
        await using var db = CreateDb();
        var company = new Company { Name = "Acme", OwnerUserId = "user-1" };
        db.Companies.Add(company);
        await db.SaveChangesAsync();

        var job = new JobApplication { JobTitle = "Backend Dev", CompanyId = company.Id, OwnerUserId = "user-1" };
        db.JobApplications.Add(job);
        await db.SaveChangesAsync();

        var controller = CreateController(db, "user-1");
        var result = await controller.SaveApplicationDrafts(job.Id, new SaveApplicationDraftsRequest(null, null, " Recruiter hello "), CancellationToken.None);

        Assert.IsType<NoContentResult>(result);
        var saved = await db.JobApplications.FirstAsync();
        Assert.Equal("Recruiter hello", saved.RecruiterMessageDraft);
    }

    private static JobApplicationsController CreateController(JobTrackerContext db, string userId)
    {
        var summarizer = new Mock<ISummarizerService>();
        summarizer.Setup(x => x.SummarizeSectionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync("generated text");
        var users = CreateUserManager();

        var controller = new JobApplicationsController(db, summarizer.Object, users.Object);
        controller.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext
            {
                User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }, "test"))
            }
        };
        return controller;
    }

    private static Mock<Microsoft.AspNetCore.Identity.UserManager<ApplicationUser>> CreateUserManager()
    {
        return TestHostFactory.CreateUserManager();
    }

    private static JobTrackerContext CreateDb()
    {
        return TestHostFactory.CreateInMemoryDb();
    }
}
