<?php

namespace App\Http\Middleware;

use App\Services\LoggingService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ApiLogger
{
    protected LoggingService $loggingService;

    public function __construct(LoggingService $loggingService)
    {
        $this->loggingService = $loggingService;
    }

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $branch = $user?->branch;

        $this->loggingService->setRequestContext(
            method: $request->method(),
            endpoint: $request->path(),
            userId: $user?->id,
            userEmail: $user?->email,
            branchId: $branch?->id ?? $user?->branch_id,
            branchName: $branch?->name,
            ipAddress: $request->ip(),
            payload: $request->except(['password', 'password_confirmation'])
        );

        return $next($request);
    }
}
