import { AuthRequest } from './auth.js'

export interface DataScope {
  role: string
  storeCode?: string
  region?: string
  dept?: string
}

export function getDataScope(req: AuthRequest): DataScope | null {
  if (!req.user) return null

  if (req.user.role === 'hq' || req.user.role === 'platform_admin' || req.user.role === 'dept') {
    return null
  }

  if (req.user.role === 'store' && req.user.storeCode) {
    return {
      role: 'store',
      storeCode: req.user.storeCode,
    }
  }

  if (req.user.role === 'regional' && req.user.region) {
    return {
      role: 'regional',
      region: req.user.region,
    }
  }

  return null
}

export function scopeStoreFilter(scope: DataScope | null, existingParams: any[]): { clause: string; params: any[] } {
  if (!scope) return { clause: '', params: existingParams }

  if (scope.role === 'store' && scope.storeCode) {
    const codes = scope.storeCode.split(',').map(s => s.trim()).filter(Boolean)
    if (codes.length === 0) return { clause: '', params: existingParams }
    const idx = existingParams.length + 1
    return {
      clause: ` AND store_code = ANY($${idx})`,
      params: [...existingParams, codes],
    }
  }

  if (scope.role === 'regional' && scope.region) {
    const codes = scope.region.split(',').map(s => s.trim()).filter(Boolean)
    if (codes.length === 0) return { clause: '', params: existingParams }
    const idx = existingParams.length + 1
    return {
      clause: ` AND store_code = ANY($${idx})`,
      params: [...existingParams, codes],
    }
  }

  return { clause: '', params: existingParams }
}
