<?php

namespace App\Http\Controllers\Admin\Office;

use App\Http\Controllers\Controller;
use App\Models\Office\Handover;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HandoverController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Handover::query()->with(['handoverUser', 'receiverUser']);
        $query->when($request->shift_date, fn($q, $v) => $q->where('shift_date', $v));
        $query->when($request->shift_type, fn($q, $v) => $q->where('shift_type', $v));

        return $this->paginate($query->latest('created_at')->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'shift_date' => 'required|date',
            'shift_type' => 'required|integer|in:1,2,3,4',
            'content' => 'required|string',
            'issues' => 'nullable|string',
        ]);
        $validated['handover_user_id'] = auth()->id();

        return $this->success(Handover::create($validated));
    }

    public function show(Handover $handover): JsonResponse
    {
        return $this->success($handover->load(['handoverUser', 'receiverUser']));
    }

    public function confirm(Handover $handover): JsonResponse
    {
        if ($handover->status === 1) {
            return $this->error('该交接班已确认', 40001);
        }
        $handover->update([
            'receiver_user_id' => auth()->id(),
            'status' => 1,
            'confirmed_at' => now(),
        ]);

        return $this->success($handover);
    }
}
