<?php

namespace App\Services;

use App\Interface\HistoryOwner;
use App\Interface\NoteOwner;
use App\Models\Note;

class NoteService {

    public function __construct(HistoryService $historyService) {
        $this->historyService = $historyService;
    }

    public function addNote(NoteOwner $owner, string $note, $is_primary = false) {
        $createdNote = $owner->notes()->create([
            'user_id' => auth()->id(),
            'note' => $note,
            'is_primary' => $is_primary
        ]);
    
        $historyOwner = $this->resolveHistoryOwner($owner);
    
        if($is_primary) {
            $this->historyService->add($historyOwner, 'Key info added: "' . $note . '"');
        } else {
            $this->historyService->add($historyOwner, 'Note added: "' . $note . '"');
        }
    
        return $createdNote;
    }

    public function deleteNote(Note $note) {
        $historyOwner = $this->resolveHistoryOwner($note->owner);

        if($note->is_primary) {
            $this->historyService->add($historyOwner, 'Key info deleted: "' . $note->note . '"');
        } else {
            $this->historyService->add($historyOwner, 'Note deleted: "' . $note->note . '"');
        }
        $note->delete();
    }

    private function resolveHistoryOwner(object $owner): HistoryOwner {
        if ($owner instanceof \App\Models\Claim\Claim) {
            return $owner->client;
        }
        if ($owner instanceof \App\Models\Dsar\Dsar) {
            return $owner->claim->client;
        }
        return $owner;
    }
}