using System.Security.Claims; using JobTrackerApi.Controllers; using JobTrackerApi.Data; using JobTrackerApi.Models; using JobTrackerApi.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Moq; using Xunit; namespace JobTrackerApi.Tests; public sealed class CompanyRelationshipTests { [Fact] public async Task Relationship_combines_owned_applications_and_contact_history() { var current = new Mock(); current.SetupGet(x => x.UserId).Returns("owner-1"); await using var db = new JobTrackerContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options, current.Object); var company = new Company { OwnerUserId = "owner-1", Name = "Acme", RecruiterName = "Rita" }; db.Companies.Add(company); await db.SaveChangesAsync(); var application = new JobApplication { OwnerUserId = "owner-1", CompanyId = company.Id, JobTitle = "Backend Developer", Status = "Interview", DateApplied = new DateTime(2026, 8, 1) }; db.JobApplications.Add(application); await db.SaveChangesAsync(); db.Correspondences.Add(new Correspondence { JobApplicationId = application.Id, From = "Rita", Direction = "inbound", Channel = "email", Subject = "Interview", Content = "See you Tuesday", Date = new DateTime(2026, 8, 10) }); await db.SaveChangesAsync(); var controller = new CompaniesController(db) { ControllerContext = new ControllerContext { HttpContext = Http("owner-1") } }; var dto = Assert.IsType(Assert.IsType((await controller.GetRelationship(company.Id, default)).Result).Value); Assert.Equal("Acme", dto.Company.Name); Assert.Equal(1, Assert.Single(dto.Applications).MessageCount); Assert.Equal("Interview", Assert.Single(dto.RecentContacts).Subject); } [Fact] public async Task Relationship_does_not_expose_another_owners_company() { var current = new Mock(); current.SetupGet(x => x.UserId).Returns("owner-1"); await using var db = new JobTrackerContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options, current.Object); var company = new Company { OwnerUserId = "owner-2", Name = "Private" }; db.Companies.Add(company); await db.SaveChangesAsync(); var controller = new CompaniesController(db) { ControllerContext = new ControllerContext { HttpContext = Http("owner-1") } }; Assert.IsType((await controller.GetRelationship(company.Id, default)).Result); } private static DefaultHttpContext Http(string userId) { var context = new DefaultHttpContext(); context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId)], "test")); return context; } }