import type { H3Event } from 'h3'
import { requireUserSession } from './auth'

/**
 * Validates that the current user has access to the specified organization/user ID
 *
 * This function works in two modes:
 *
 * 1. WITHOUT organizations (enableOrganizations: false):
 *    - organizationId should be the user's own ID
 *    - Validates that the authenticated user matches the organizationId
 *
 * 2. WITH organizations (enableOrganizations: true):
 *    - organizationId is an actual Better Auth organization ID
 *    - Validates that the user is a member/owner of that organization
 *    - TODO: Implement Better Auth organization membership checks
 *
 * @param event - H3 event from the API route
 * @param organizationId - The organization/user ID to validate access for
 * @returns The authenticated session
 * @throws 400 if organizationId is missing
 * @throws 403 if user doesn't have access to the organization
 */
export async function validateOrganizationAccess(event: H3Event, organizationId: string) {
  if (!organizationId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Organization ID is required'
    })
  }

  // Get authenticated user
  const session = await requireUserSession(event)
  const config = useRuntimeConfig()
  const enableOrganizations = config.public.saas?.enableOrganizations ?? false

  if (!enableOrganizations) {
    // Mode 1: Without organizations
    // The organizationId should be the user's own ID
    if (session.user.id !== organizationId) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Access denied: You can only access your own resources'
      })
    }
  } else {
    // Mode 2: With organizations
    // TODO: Implement Better Auth organization membership validation
    // For now, we'll allow access if the user is authenticated
    // Future implementation should check:
    // - Is user a member of this organization?
    // - What is their role? (owner, admin, member)
    // - Do they have permission for this action?

    console.warn('[organizationValidation] Organization membership validation not yet implemented')

    // Placeholder validation - replace with actual Better Auth org checks
    // const hasAccess = await checkOrganizationMembership(session.user.id, organizationId)
    // if (!hasAccess) {
    //   throw createError({
    //     statusCode: 403,
    //     statusMessage: 'Access denied: You are not a member of this organization'
    //   })
    // }
  }

  return session
}

/**
 * Validates that the current user is the owner of the specified organization
 *
 * For non-organization mode, this is equivalent to validateOrganizationAccess
 * For organization mode, this specifically checks for owner role
 *
 * @param event - H3 event from the API route
 * @param organizationId - The organization/user ID to validate ownership for
 * @returns The authenticated session
 */
export async function validateOrganizationOwnership(event: H3Event, organizationId: string) {
  const session = await validateOrganizationAccess(event, organizationId)
  const config = useRuntimeConfig()
  const enableOrganizations = config.public.saas?.enableOrganizations ?? false

  if (enableOrganizations) {
    // TODO: Implement owner-specific validation for organizations
    // const role = await getOrganizationRole(session.user.id, organizationId)
    // if (role !== 'owner') {
    //   throw createError({
    //     statusCode: 403,
    //     statusMessage: 'Access denied: Only organization owners can perform this action'
    //   })
    // }

    console.warn('[organizationValidation] Organization ownership validation not yet implemented')
  }

  return session
}
