<?php

namespace App\Http\Controllers;

use App\Models\DataSyncClient;
use App\Services\DataSyncService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SyncReceiveController extends Controller
{
    public function __invoke(Request $request, DataSyncService $sync): JsonResponse
    {
        $validated = $request->validate([
            'token' => ['required', 'string'],
            'payload' => ['required', 'array'],
        ]);

        $client = DataSyncClient::withoutGlobalScopes()
            ->where('token_hash', hash('sha256', $validated['token']))
            ->where('is_active', true)
            ->first();

        if (! $client) {
            return response()->json([
                'ok' => false,
                'message' => 'Invalid or inactive sync token.',
            ], 403);
        }

        $client->load('tenant');
        $log = $sync->importPackage($client->tenant, $validated['payload'], null, $client->id, 'receive');
        $client->update(['last_synced_at' => now()]);

        return response()->json([
            'ok' => true,
            'records' => $log->records_count,
            'status' => $log->status,
        ]);
    }
}
