<?php

namespace Datalumo\PhpSdk\Resources;

use Datalumo\PhpSdk\DataObjects\Entry;
use Datalumo\PhpSdk\DataObjects\PaginatedResponse;
use Datalumo\PhpSdk\HttpClient;

class EntryResource
{
    public function __construct(
        private readonly HttpClient $client,
        private readonly string $collectionId,
    ) {}

    public function list(int $page = 1): PaginatedResponse
    {
        return PaginatedResponse::fromArray(
            $this->client->get("collections/{$this->collectionId}/entries", ['page' => $page]),
            Entry::fromArray(...),
        );
    }

    /**
     * @param array{
     *     raw_text: string,
     *     title?: string,
     *     meta?: array,

     *     source_url?: string,
     *     source_type?: string,
     *     source_id?: string,
     * } $data
     */
    public function create(array $data): Entry
    {
        return Entry::fromArray(
            $this->client->post("collections/{$this->collectionId}/entries", $data)['data'],
        );
    }

    /**
     * @param array{
     *     raw_text: string,
     *     source_type: string,
     *     source_id: string,
     *     title?: string,
     *     meta?: array,

     *     source_url?: string,
     * } $data
     */
    public function upsert(array $data): Entry
    {
        return Entry::fromArray(
            $this->client->put("collections/{$this->collectionId}/entries/upsert", $data)['data'],
        );
    }

    /**
     * @param array<array{
     *     raw_text: string,
     *     title?: string,
     *     meta?: array,

     *     source_url?: string,
     *     source_type?: string,
     *     source_id?: string,
     * }> $entries
     * @return array{created: int, updated: int}
     */
    public function batchUpsert(array $entries): array
    {
        return $this->client->post("collections/{$this->collectionId}/entries/batch", [
            'entries' => $entries,
        ]);
    }

    /**
     * @param array{
     *     raw_text?: string,
     *     title?: string,
     *     meta?: array,

     *     source_url?: string,
     *     source_type?: string,
     *     source_id?: string,
     * } $data
     */
    public function update(string $entryId, array $data): Entry
    {
        return Entry::fromArray(
            $this->client->patch("collections/{$this->collectionId}/entries/{$entryId}", $data)['data'],
        );
    }

    public function delete(string $entryId): void
    {
        $this->client->delete("collections/{$this->collectionId}/entries/{$entryId}");
    }

    public function deleteBySource(string $sourceType, string $sourceId): void
    {
        $this->client->delete("collections/{$this->collectionId}/entries/by-source/{$sourceType}/{$sourceId}");
    }
}
