<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Evidence;
use App\Services\ActivityLogger;
use App\Services\CustodyService;
use Illuminate\Http\Request;
class EvidenceController extends Controller
{
    public function store(Request $request)
    {
        $this->authorize('create', Evidence::class);
        $data = $request->validate([
            'case_id' => ['required','exists:cases,id'],
            'type' => ['required','in:image,video,audio,document,other'],
            'title' => ['nullable','string','max:200'],
            'description' => ['nullable','string'],
            'visibility' => ['required','in:internal,client_visible,restricted'],
            'file' => ['required','file','max:51200'],
        ]);
        $file = $request->file('file');
        $storedPath = $file->store('evidences/' . $request->case_id, 'public');
        $evidence = Evidence::create([
            'case_id' => $request->case_id,
            'uploaded_by' => $request->user()->id,
            'type' => $request->type,
            'title' => $request->title,
            'description' => $request->description,
            'source' => 'android-app',
            'visibility' => $request->visibility,
            'file_name' => $file->getClientOriginalName(),
            'file_path' => $storedPath,
            'mime_type' => $file->getMimeType(),
            'extension' => $file->getClientOriginalExtension(),
            'file_size' => $file->getSize(),
            'sha256_hash' => hash_file('sha256', $file->getRealPath()),
        ]);
        CustodyService::record($evidence, 'uploaded', $request->user()->id, 'Upload API mobile', $request->ip());
        ActivityLogger::log($request->user()->id, 'evidences', 'api_create', Evidence::class, $evidence->id, 'Evidência criada via API', $request->ip(), $request->userAgent(), ['case_id' => $request->case_id]);
        return response()->json([
            'success' => true,
            'message' => 'Evidência criada com sucesso',
            'data' => $evidence,
        ], 201);
    }
    public function custody(Request $request, Evidence $evidence)
    {
        $this->authorize('view', $evidence);
        $events = $evidence->custodyEvents()->with('performer')->latest('event_at')->paginate($request->integer('per_page', 20));
        return response()->json([
            'success' => true,
            'message' => 'Custódia carregada com sucesso',
            'data' => ['evidence' => $evidence, 'events' => $events->items()],
            'meta' => [
                'current_page' => $events->currentPage(),
                'per_page' => $events->perPage(),
                'total' => $events->total(),
                'last_page' => $events->lastPage(),
            ],
        ]);
    }
}
