<?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 updateStatus(WillsCase $case, int $statusId): bool {
        if ($case->status_id === $statusId) {
            return false;
        }

        $oldStatus = $case->status;

        $case->update(['status_id' => $statusId]);
        $case->updateStatus($statusId);

        $newStatus = $case->fresh()->status;

        $this->history->add($case, 'Status changed from "' . ($oldStatus->display_name ?? '-') . '" to "' . ($newStatus->display_name ?? '-') . '"', [
            'from_status_id' => $oldStatus?->id,
            'from_status'    => $oldStatus?->display_name,
            'to_status_id'   => $statusId,
            'to_status'      => $newStatus?->display_name,
        ]);

        return true;
    }

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

        // Snapshot every written field so the audit captures all changes.
        $before = $case->only(array_keys($data));

        $case->update($data);

        foreach ($case->getChanges() as $field => $newValue) {
            if (in_array($field, ['updated_at', 'created_at'])) {
                continue;
            }
            $context['changed'][$field] = [
                'from' => $before[$field] ?? null,
                'to'   => $newValue,
            ];
        }

        $label = 'Wills & Trusts case updated';
        if (!empty($context['changed'])) {
            $parts = [];
            if (isset($context['changed']['is_open'])) {
                $change = $context['changed']['is_open'];
                $parts[] = 'Open/closed changed from "' . ($change['from'] ? 'open' : 'closed') . '" to "' . ($change['to'] ? 'open' : 'closed') . '"';
            }

            $otherCount = count(array_diff_key($context['changed'], ['is_open' => true]));
            if ($otherCount > 0) {
                $parts[] = $otherCount . ' other field(s) updated';
            }

            $label = 'Wills & Trusts case updated: ' . implode('; ', $parts);
        }

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

        return $case;
    }
}
