<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\SyncService;
use App\Traits\ApiResponse;
use Carbon\Carbon;
use Illuminate\Http\Request;

class SyncController extends Controller
{
    use ApiResponse;

    protected $syncService;

    public function __construct(SyncService $syncService)
    {
        $this->syncService = $syncService;
    }

    public function getDeltaSync(Request $request)
    {   
        $lastSync = $request->query('last_sync');
        try {
            $currentTime = Carbon::now();    

            $data = $this->syncService->getDeltaSync($lastSync);

            $this->syncService->updateServerTime($currentTime);
            return response()->json([
                'status' => 'success',
                'server_time' => $currentTime->toDateTimeString(),
                'data' => $data
            ], 200);
        } catch(\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function batchUpSync(Request $request)
    {
        $request->validate([
            'batch_id' => 'required|string',
            'items'    => 'required|array',
        ]);

        $payload = $request->all();

        $payload['items'] = array_map(function($item) {
            return is_string($item) ? json_decode($item, true) : $item;
        }, $payload['items']);

        try {
            $report = $this->syncService->processBatchSync($payload);

            return response()->json([
                'status'   => 'success',
                'batch_id' => $request->batch_id,
                'report'   => $report,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status'  => 'error',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
