<?php

namespace App\Modules\Valuation\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Valuation\Http\Requests\CreateValuationAdjustment;
use App\Modules\Valuation\Http\Requests\UpdateValuationAdjustment;
use App\Modules\Valuation\Http\Resources\ValuationAdjustmentList;
use App\Modules\Valuation\Http\Resources\ValuationAdjustmentView;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mtc\MercuryDataModels\ValuationAdjustment;

class ValuationAdjustmentController extends Controller
{
    public function index(): ValuationAdjustmentList
    {
        return new ValuationAdjustmentList(ValuationAdjustment::query()->paginate());
    }

    public function store(CreateValuationAdjustment $request): ValuationAdjustmentView
    {
        $adjustment = ValuationAdjustment::query()->create($request->validated());
        return new ValuationAdjustmentView($adjustment);
    }

    public function show(ValuationAdjustment $valuationAdjustment): ValuationAdjustmentView
    {
        return new ValuationAdjustmentView($valuationAdjustment);
    }

    public function update(
        UpdateValuationAdjustment $request,
        ValuationAdjustment $valuationAdjustment
    ): ValuationAdjustmentView {
        $valuationAdjustment->update($request->validated());

        $valuationAdjustment->rules()
            ->whereNotIn('id', collect($request->input('rules', []))->pluck('value.id'))
            ->delete();

        collect($request->input('rules', []))
            ->each(fn(array $rule) => $valuationAdjustment->rules()->updateOrCreate(
                [
                'id' => $rule['value']['id']
                ],
                $rule['value']
            ));

        return new ValuationAdjustmentView($valuationAdjustment);
    }

    public function destroy(ValuationAdjustment $valuationAdjustment): Response
    {
        $valuationAdjustment->delete();
        return response('ok');
    }
}
