<?php

namespace App\Http\Controllers;

use App\Models\CaseObject;
use App\Models\ClientCase;
use App\Models\Contract;
use Illuminate\Http\Request;

class CaseObjectController extends Controller
{
    public function store(ClientCase $clientCase, string $uuid, Request $request)
    {
        $contract = Contract::where('uuid', $uuid)->where('client_case_id', $clientCase->id)->firstOrFail();
        $validated = $request->validate([
            'reference' => 'nullable|string|max:125',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:125',
        ]);

        $contract->objects()->create($validated);

        return to_route('clientCase.show', $clientCase)->with('success', 'Object created.');
    }

    public function update(ClientCase $clientCase, int $id, Request $request)
    {
        $object = CaseObject::where('id', $id)
            ->whereHas('contract', fn ($q) => $q->where('client_case_id', $clientCase->id))
            ->firstOrFail();

        $validated = $request->validate([
            'reference' => 'nullable|string|max:125',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:125',
        ]);

        $object->update($validated);

        return to_route('clientCase.show', $clientCase)->with('success', 'Object updated.');
    }

    public function destroy(ClientCase $clientCase, int $id)
    {
        $object = CaseObject::where('id', $id)
            ->whereHas('contract', fn ($q) => $q->where('client_case_id', $clientCase->id))
            ->firstOrFail();

        $object->delete();

        return to_route('clientCase.show', $clientCase)->with('success', 'Object deleted.');
    }
}
