using Fitness_core_BE.Interfaces; using Fitness_core_BE.Models; using Microsoft.EntityFrameworkCore; namespace Fitness_core_BE.Repos { public class PaymentRepository : IPaymentRepository { // Row-split entity: member payments (FK_CustomerInvoiceId set) live in the tenant DB, // platform-billing payments (FK_ClientInvoiceId set) live in the central DB. private readonly TenantDbContext _context; private readonly CentralDbContext _central; public PaymentRepository(TenantDbContext context, CentralDbContext central) { _context = context; _central = central; } public async Task CreatePaymentAttemptAsync(PaymentTransaction attempt) { if (attempt.FK_ClientInvoiceId.HasValue) await _central.PaymentTransactions.AddAsync(attempt); else await _context.PaymentTransactions.AddAsync(attempt); return attempt; } public async Task GetPaymentByIdAsync(Guid attemptId) { var tenant = await _context.PaymentTransactions .AsNoTracking() .Include(p => p.CustomerCard) .Include(p => p.CustomerInvoice) .FirstOrDefaultAsync(p => p.AttemptId == attemptId && p.IsActive == true); if (tenant != null) return tenant; return await _central.PaymentTransactions .AsNoTracking() .Include(p => p.ClientInvoice) .FirstOrDefaultAsync(p => p.AttemptId == attemptId && p.IsActive == true); } public async Task> GetPaymentsByCustomerInvoiceIdAsync(Guid customerInvoiceId) { return await _context.PaymentTransactions .AsNoTracking() .Include(p => p.CustomerCard) .Where(p => p.FK_CustomerInvoiceId == customerInvoiceId && p.IsActive == true) .OrderByDescending(p => p.PayDate) .ToListAsync(); } public async Task> GetPaymentsByClientInvoiceIdAsync(Guid clientInvoiceId) { return await _central.PaymentTransactions .AsNoTracking() .Where(p => p.FK_ClientInvoiceId == clientInvoiceId && p.IsActive == true) .OrderByDescending(p => p.PayDate) .ToListAsync(); } public async Task UpdatePaymentAttemptAsync(PaymentTransaction attempt) { if (attempt.FK_ClientInvoiceId.HasValue) _central.PaymentTransactions.Update(attempt); else _context.PaymentTransactions.Update(attempt); return attempt; } public async Task GetApprovedPaidAmountAsync(Guid customerInvoiceId) { return await _context.PaymentTransactions .AsNoTracking() .Where(p => p.FK_CustomerInvoiceId == customerInvoiceId && p.IsApproved == true && p.IsActive == true) .Select(p => (decimal?)p.PayAmount) .SumAsync() ?? 0m; } } }