<?php

namespace App\Http\Controllers\Api\V2;

use App\Http\Controllers\Controller;
use App\Models\Victim;
use App\Services\Integrations\NsrRegistryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class NsrApiController extends Controller
{
    public function pushCase(Request $request, NsrRegistryService $service)
    {
        $validated = $request->validate([
            'victim_uuid' => ['nullable', 'string'],
            'victim_id' => ['nullable'],
            'record_type' => ['nullable', 'string', 'max:50'],
        ]);

        $victim = Victim::query()
            ->when(!empty($validated['victim_uuid']) && Schema::hasColumn((new Victim())->getTable(), 'uuid'), function ($query) use ($validated) {
                return $query->where('uuid', $validated['victim_uuid']);
            })
            ->when(empty($validated['victim_uuid']) && !empty($validated['victim_id']), function ($query) use ($validated) {
                if (Str::isUuid((string) $validated['victim_id']) && Schema::hasColumn((new Victim())->getTable(), 'uuid')) {
                    return $query->where('uuid', $validated['victim_id']);
                }
                return $query->where('id', $validated['victim_id']);
            })
            ->firstOrFail();

        $log = $service->pushVictim($victim, $validated['record_type'] ?? 'case');

        return response()->json([
            'success' => $log->status === 'success',
            'message' => $log->status === 'success' ? 'Record shared with NSR.' : 'Record sharing failed or is not configured.',
            'log_uuid' => $log->uuid,
            'status' => $log->status,
        ], $log->status === 'success' ? 200 : 422);
    }
}
