<?php

namespace App\Http\Controllers;

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

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

        $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');
        $payload = $sync->exportPackage($client->tenant);
        $records = collect($payload['data'])->sum(fn ($rows) => count((array) $rows));

        DataSyncPackage::create([
            'tenant_id' => $client->tenant_id,
            'data_sync_client_id' => $client->id,
            'direction' => 'pull_export',
            'status' => 'completed',
            'records_count' => $records,
            'summary' => collect($payload['data'])->map(fn ($rows) => count((array) $rows))->all(),
            'completed_at' => now(),
        ]);

        $client->update(['last_synced_at' => now()]);

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