<?php

namespace App\Services;

use App\Models\Client\Client;
use App\Models\PensionCase\PensionCase;
use App\Models\PensionCase\PensionCaseComment;
use App\Models\PensionCase\PensionCaseInterim;

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

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

        $this->history->add($case, 'Pension case created', [
            'case_number' => $case->case_number,
            'sf_case_id' => $case->sf_case_id,
        ]);

        $this->history->add($client, 'Pension case created', [
            'case_number' => $case->case_number,
            'pension_case_id' => $case->id,
        ]);

        return $case;
    }

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

        // Track settlement status changes explicitly
        if (isset($data['settlement_status']) && $data['settlement_status'] !== $case->settlement_status) {
            $context['changed']['settlement_status'] = [
                'from' => $case->settlement_status,
                'to' => $data['settlement_status'],
            ];
        }

        foreach (['bank_claim_status', 'fos_claim_status', 'fscs_claim_status', 'is_open', 'is_closed'] as $field) {
            if (isset($data[$field]) && $data[$field] !== $case->$field) {
                $context['changed'][$field] = [
                    'from' => $case->$field,
                    'to' => $data[$field],
                ];
            }
        }

        $case->update($data);

        $label = 'Pension case updated';
        if (!empty($context['changed'])) {
            $parts = [];
            $fieldLabels = [
                'settlement_status' => 'Settlement status',
                'bank_claim_status' => 'Bank claim status',
                'fos_claim_status'  => 'FOS claim status',
                'fscs_claim_status' => 'FSCS claim status',
                'is_open'           => 'Open/closed',
                'is_closed'         => 'Closed flag',
            ];
            foreach ($context['changed'] as $field => $change) {
                $name = $fieldLabels[$field] ?? $field;
                $parts[] = $name . ' changed from "' . ($change['from'] ?? '—') . '" to "' . ($change['to'] ?? '—') . '"';
            }
            $label = implode('; ', $parts);
        }

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

        return $case;
    }

    public function addComment(PensionCase $case, string $text): PensionCaseComment {
        $comment = $case->comments()->create([
            'pension_case_id' => $case->id,
            'comment_created_by' => auth()->id(),
            'comment_created_at' => now(),
            'comment_text' => $text,
        ]);

        $this->history->add($case, 'Comment added', [
            'comment_id' => $comment->id,
            'preview' => mb_substr($text, 0, 100),
        ]);

        return $comment;
    }

    public function addInterim(PensionCase $case, array $data): PensionCaseInterim {
        $interim = $case->interims()->create($data);

        $this->history->add($case, 'Interim payment #' . $interim->interim_number . ' added', [
            'interim_number' => $interim->interim_number,
            'interim_amount' => $interim->interim_amount,
            'interim_date' => $interim->interim_date?->format('Y-m-d'),
        ]);

        return $interim;
    }

    public function deleteInterim(PensionCaseInterim $interim): void {
        $case = $interim->pensionCase;

        $this->history->add($case, 'Interim payment #' . $interim->interim_number . ' deleted', [
            'interim_number' => $interim->interim_number,
            'interim_amount' => $interim->interim_amount,
        ]);

        $interim->delete();
    }
}
