<?php

namespace App\Services;

use App\Models\Client\Client;
use App\Models\WillsCase\WillsCase;

class WillsCaseService {
    public function __construct(protected HistoryService $history) {}

    public function create(Client $client, array $data): WillsCase {
        $case = $client->willsCases()->create($data);

        $this->history->add($case, 'Wills & Trusts case created', [
            'case_number' => $case->case_number,
        ]);

        $this->history->add($client, 'Wills & Trusts case created', [
            'case_number'   => $case->case_number,
            'wills_case_id' => $case->id,
        ]);

        return $case;
    }

    public function update(WillsCase $case, array $data): WillsCase {
        $context = [];

        if (isset($data['is_open']) && $data['is_open'] !== $case->is_open) {
            $context['changed']['is_open'] = [
                'from' => $case->is_open,
                'to'   => $data['is_open'],
            ];
        }

        $case->update($data);

        $label = 'Wills & Trusts case updated';
        if (!empty($context['changed'])) {
            $parts = [];
            foreach ($context['changed'] as $field => $change) {
                $fieldLabels = ['is_open' => 'Open/closed'];
                $name = $fieldLabels[$field] ?? $field;
                $parts[] = $name . ' changed from "' . ($change['from'] ? 'open' : 'closed') . '" to "' . ($change['to'] ? 'open' : 'closed') . '"';
            }
            $label = implode('; ', $parts);
        }

        $this->history->add($case, $label, $context);

        return $case;
    }
}
