<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class RosterController extends Controller
{
    /**
     * GET /api/v1/roster?since=<iso> — employee delta sync (down).
     * Omit `since` (or pass full=1) for a full snapshot.
     */
    public function index(Request $request)
    {
        $since = $request->query('since');
        $full = $request->boolean('full') || ! $since;

        if ($full) {
            $employees = Employee::query()->get();
            $deleted = [];
        } else {
            $sinceTs = Carbon::parse($since);
            $employees = Employee::query()->where('updated_at', '>=', $sinceTs)->get();
            $deleted = Employee::onlyTrashed()->where('deleted_at', '>=', $sinceTs)->pluck('emp_id');
        }

        return response()->json([
            'employees' => $employees->map(fn (Employee $e) => [
                'emp_id' => $e->emp_id,
                'name' => $e->name,
                'active' => $e->active,
                'consent_on' => $e->consent_on?->toDateString(),
                'updated_at' => $e->updated_at?->toIso8601String(),
            ])->values(),
            'deleted' => collect($deleted)->values(),
            'server_time' => now()->toIso8601String(),
        ]);
    }
}
