import { prisma } from './db'
import { UserPayload } from './auth'

/**
 * Get the tenantId filter for data queries.
 * - SERVER_ADMIN: no filter (sees everything)
 * - All others: filter by their tenantId
 */
export function getTenantFilter(user: UserPayload): Record<string, any> {
  if (user.role === 'SERVER_ADMIN') return {}
  if (!user.tenantId) return { ownerId: user.id } // no tenant → only own projects
  // Tenant user: see tenant projects + own legacy projects (tenantId=null)
  return {
    OR: [
      { tenantId: user.tenantId },
      { ownerId: user.id, tenantId: null },
    ],
  }
}

/**
 * Check if a user has access to a specific project.
 * Returns the project if access is granted, null otherwise.
 */
export async function getProjectWithTenantCheck(projectId: string, user: UserPayload) {
  const project = await (prisma as any).project.findUnique({
    where: { id: projectId },
  })
  if (!project) return null

  // SERVER_ADMIN can access all projects
  if (user.role === 'SERVER_ADMIN') return project

  // Projects without tenantId (legacy): allow if user is the owner
  if (!project.tenantId) {
    if (project.ownerId === user.id) return project
    return null
  }

  // All others: must belong to same tenant
  if (project.tenantId !== user.tenantId) return null

  return project
}
