# PowerShell script to fix all remaining clientId issues in article_approval_flows
# Usage: .\fix_all_article_approval_flows_final2.ps1 <file_path>

param(
    [Parameter(Mandatory=$true)]
    [string]$FilePath
)

if (-not (Test-Path $FilePath)) {
    Write-Error "File not found: $FilePath"
    exit 1
}

Write-Host "Fixing all remaining clientId issues in: $FilePath"

# Read file content
$Content = Get-Content $FilePath -Raw

# Find all methods that use clientId but don't have extraction logic
$MethodPattern = 'func \(_i \*(\w+)Service\) (\w+)\(authToken string, ([^)]+)\) \{[^}]*return _i\.(\w+)Repository\.(\w+)\(clientId,'

$Matches = [regex]::Matches($Content, $MethodPattern)

foreach ($Match in $Matches) {
    $ServiceName = $Match.Groups[1].Value
    $MethodName = $Match.Groups[2].Value
    $Parameters = $Match.Groups[3].Value
    
    Write-Host "Fixing method: $MethodName"
    
    # Create the clientId extraction logic
    $ExtractionLogic = @"
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepository, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	if clientId == nil {
		return nil, errors.New("clientId not found in auth token")
	}

"@
    
    # Replace the method opening with extraction logic
    $OldMethodStart = "func (_i *${ServiceName}Service) ${MethodName}(authToken string, ${Parameters}) {"
    $NewMethodStart = "func (_i *${ServiceName}Service) ${MethodName}(authToken string, ${Parameters}) {${ExtractionLogic}"
    
    $Content = $Content -replace [regex]::Escape($OldMethodStart), $NewMethodStart
}

# Write updated content
Set-Content $FilePath $Content -NoNewline

Write-Host "All remaining clientId issues fixed."
