using Microsoft.EntityFrameworkCore;
using ColaFlow.Modules.ProjectManagement.Application.Services;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;

namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Services;

/// <summary>
/// Implementation of project permission checking service
/// </summary>
public sealed class ProjectPermissionService : IProjectPermissionService
{
    private readonly PMDbContext _dbContext;

    public ProjectPermissionService(PMDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// Checks if a user has permission to access a project
    /// Currently checks if user is the project owner
    /// Multi-tenant isolation is enforced by the DbContext query filter
    /// TODO: Extend to check ProjectMember table when implemented
    /// </summary>
    public async Task<bool> IsUserProjectMemberAsync(Guid userId, Guid projectId, CancellationToken cancellationToken = default)
    {
        // Query will automatically apply tenant filter from PMDbContext
        var project = await _dbContext.Projects
            .AsNoTracking()
            .FirstOrDefaultAsync(p => p.Id.Value == projectId, cancellationToken);

        if (project == null)
        {
            // Project doesn't exist or user's tenant doesn't have access
            return false;
        }

        // Check if user is the project owner
        // TODO: When ProjectMember table is implemented, also check:
        // await _dbContext.ProjectMembers.AnyAsync(pm => pm.ProjectId == projectId && pm.UserId == userId)
        return project.OwnerId.Value == userId;
    }
}
