using vendorApproverBackend.Data; using vendorApproverBackend.DTOs; using vendorApproverBackend.Responses; using Microsoft.EntityFrameworkCore; namespace vendorApproverBackend.Services; public class LinkedAccountService { private readonly DataContext _context; private readonly UserService _userService; private readonly TokenService _tokenService; public LinkedAccountService(DataContext context, UserService userService, TokenService tokenService) { _context = context; _userService = userService; _tokenService = tokenService; } // GET all users that have this deviceId in their list public async Task> GetLinkedAccountsAsync(string deviceId) { var users = await _context.Users .Include(u => u.Image) .Where(u => u.DeviceIds.Contains(deviceId) && !u.Deleted && u.Active) .ToListAsync(); return users.Select(u => new LinkedAccountDto { UserId = u.Id, Email = u.Email, Role = u.Role, Type = u.Type, ProfileImageUrl = u.Image != null ? u.Image.Url : null }).ToList(); } // FORGET: remove deviceId from the current user's list public async Task ForgetAccountAsync(long userId, string deviceId) { var user = await _context.Users.FindAsync(userId); if (user == null) return false; if (!user.DeviceIds.Contains(deviceId)) return false; user.DeviceIds.Remove(deviceId); await _userService.UpdateUserAsync(user); return true; } // SWITCH: get user by email (no password), return JWT public async Task SwitchAccountAsync(string email, string deviceId) { var user = await _userService.FindByEmailAsync(email); if (user == null) return null; if (!user.DeviceIds.Contains(deviceId)) return null; if (!user.Active) return null; if (user.Deleted) return null; var accessToken = _tokenService.CreateToken(user); return new JwtResponse( accessToken, "placeholder-refresh-token", user.Role, user.Device?.DeviceId, user.Device?.DeviceType, user.Device?.Ip, DateTime.UtcNow.AddDays(7) ); } }