<?php

namespace App\Modules\Customization\CustomFields\Repositories;

use App\Modules\Customization\CustomFields\Models\CustomFieldValue;

class CustomFieldValueRepository
{
    /**
     * @return array<string, string|null> slug => value
     */
    public function valuesBySlugForEntity(int $tenantId, string $entityType, int $entityId): array
    {
        $rows = CustomFieldValue::query()
            ->where('tenant_id', $tenantId)
            ->where('entity_type', $entityType)
            ->where('entity_id', $entityId)
            ->with('field:id,slug')
            ->get(['id', 'custom_field_id', 'value']);

        $out = [];
        foreach ($rows as $row) {
            if ($row->field !== null) {
                $out[$row->field->slug] = $row->value;
            }
        }

        return $out;
    }

    public function upsertValue(
        int $tenantId,
        int $customFieldId,
        string $entityType,
        int $entityId,
        ?string $value,
    ): void {
        CustomFieldValue::query()->updateOrCreate(
            [
                'custom_field_id' => $customFieldId,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
            ],
            [
                'tenant_id' => $tenantId,
                'value' => $value,
            ],
        );
    }

    public function deleteForEntity(int $tenantId, string $entityType, int $entityId): void
    {
        CustomFieldValue::query()
            ->where('tenant_id', $tenantId)
            ->where('entity_type', $entityType)
            ->where('entity_id', $entityId)
            ->delete();
    }

    /**
     * @return list<int>
     */
    public function searchEntityIdsByValue(int $tenantId, string $entityType, string $term): array
    {
        $like = '%'.addcslashes($term, '%_\\').'%';

        return CustomFieldValue::query()
            ->where('tenant_id', $tenantId)
            ->where('entity_type', $entityType)
            ->where('value', 'like', $like)
            ->pluck('entity_id')
            ->unique()
            ->values()
            ->all();
    }
}
