<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\FaceVerification;
use App\Support\FaceVerificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;

class FaceVerificationController extends Controller
{
    /**
     * Serve a face capture to its owner or an admin only. Face images live
     * on the private disk; legacy captures on the public disk still resolve.
     */
    public function image(Request $request, FaceVerification $faceVerification)
    {
        $user = $request->user();

        abort_unless($user->is_admin || $faceVerification->user_id === $user->id, 403);

        foreach (['local', 'public'] as $disk) {
            if (Storage::disk($disk)->exists($faceVerification->face_image_path)) {
                return Storage::disk($disk)->response($faceVerification->face_image_path);
            }
        }

        abort(404);
    }

    public function store(Request $request)
    {
        $data = $request->validate(['face_image' => ['required', 'string']]);

        try {
            $verification = app(FaceVerificationService::class)
                ->storeCapture($request, $request->user(), $data['face_image'], 'profile');
        } catch (InvalidArgumentException $exception) {
            return back()->withErrors(['face_image' => $exception->getMessage()]);
        }

        return back()->with('success', $verification->status === 'duplicate_review'
            ? 'Face verification submitted and sent for duplicate review.'
            : 'Face verification submitted for admin review.');
    }
}
