<?php

namespace App\Services;

use App\Models\Document\Document;
use App\Models\Dsar\Dsar;
use App\Models\Print\PrintQueueItem;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class PrintQueueService {

    public function add(Document $document): PrintQueueItem {
        return PrintQueueItem::firstOrCreate([
            'solicitor_id' => $document->solicitor_id,
            'document_id'  => $document->id,
            'owner_id' => $document->owner->getKey(),
            'owner_type' => $document->owner->getMorphClass()
        ], [
            'user_id' => auth()->id(),
        ]);
    }

    public function addPath(string $path, $owner): PrintQueueItem {
        return PrintQueueItem::firstOrCreate([
            'solicitor_id' => $owner->solicitor_id ?? null,
            'file_path'    => $path,
        ], [
            'owner_type' => get_class($owner),
            'owner_id'   => $owner->id,
            'user_id'    => auth()->id(),
        ]);
    }

    public function remove(int $id): void {
        PrintQueueItem::findOrFail($id)->delete();
    }

    public function removeMany(array $ids): void {
        PrintQueueItem::whereIn('id', $ids)->delete();
    }

    public function clear(): void {
        PrintQueueItem::query()->delete();
    }

    public function all(): Collection {
        return PrintQueueItem::with([
            'document.owner',
            'document.type',
            'owner' => function (MorphTo $morphTo) {
                $morphTo->morphWith([
                    Dsar::class => ['claim.client'],
                ]);
            },
            'user',
        ])->orderByDesc('created_at')->get();
    }

    public function has(Document $document): bool {
        return PrintQueueItem::where('document_id', $document->id)->exists();
    }

    public function hasPath(string $path): bool {
        return PrintQueueItem::where('file_path', $path)->exists();
    }
}
