<?php

namespace MintyPHP\Repository\CustomField;

use MintyPHP\DB;

class UserCustomFieldValueRepository
{
    private static function unwrapList($rows): array
    {
        if (!is_array($rows)) {
            return [];
        }
        $list = [];
        foreach ($rows as $row) {
            $item = $row['user_custom_field_values'] ?? null;
            if (is_array($item)) {
                $list[] = $item;
            }
        }
        return $list;
    }

    public static function listByUserAndDefinitionIds(int $userId, array $definitionIds): array
    {
        if ($userId <= 0) {
            return [];
        }
        $definitionIds = array_values(array_unique(array_map('intval', $definitionIds)));
        $definitionIds = array_values(array_filter($definitionIds, static fn ($id) => $id > 0));
        if (!$definitionIds) {
            return [];
        }
        $rows = DB::select(
            'select id, user_id, definition_id, value_text, value_bool, value_date, option_id, created, modified ' .
            'from user_custom_field_values where user_id = ? and definition_id in (???)',
            (string) $userId,
            $definitionIds
        );
        return self::unwrapList($rows);
    }

    public static function upsertScalarValue(int $userId, int $definitionId, array $typedValue): int|false
    {
        if ($userId <= 0 || $definitionId <= 0) {
            return false;
        }
        $existingId = DB::selectValue(
            'select id from user_custom_field_values where user_id = ? and definition_id = ? limit 1',
            (string) $userId,
            (string) $definitionId
        );

        $valueText = array_key_exists('value_text', $typedValue) ? $typedValue['value_text'] : null;
        $valueBool = array_key_exists('value_bool', $typedValue) ? $typedValue['value_bool'] : null;
        $valueDate = array_key_exists('value_date', $typedValue) ? $typedValue['value_date'] : null;
        $optionId = array_key_exists('option_id', $typedValue) ? $typedValue['option_id'] : null;

        if ($existingId) {
            $updated = DB::update(
                'update user_custom_field_values set value_text = ?, value_bool = ?, value_date = ?, option_id = ? where id = ?',
                $valueText,
                $valueBool !== null ? (string) ((int) $valueBool) : null,
                $valueDate,
                $optionId !== null ? (string) ((int) $optionId) : null,
                (string) ((int) $existingId)
            );
            return $updated !== false ? (int) $existingId : false;
        }

        return DB::insert(
            'insert into user_custom_field_values (user_id, definition_id, value_text, value_bool, value_date, option_id, created) values (?,?,?,?,?,?,NOW())',
            (string) $userId,
            (string) $definitionId,
            $valueText,
            $valueBool !== null ? (string) ((int) $valueBool) : null,
            $valueDate,
            $optionId !== null ? (string) ((int) $optionId) : null
        );
    }

    public static function deleteByUserAndDefinitionIds(int $userId, array $definitionIds): bool
    {
        if ($userId <= 0) {
            return false;
        }
        $definitionIds = array_values(array_unique(array_map('intval', $definitionIds)));
        $definitionIds = array_values(array_filter($definitionIds, static fn ($id) => $id > 0));
        if (!$definitionIds) {
            return true;
        }
        $result = DB::delete(
            'delete from user_custom_field_values where user_id = ? and definition_id in (???)',
            (string) $userId,
            $definitionIds
        );
        return $result !== false;
    }

    public static function deleteByUserOutsideTenantIds(int $userId, array $tenantIds): bool
    {
        if ($userId <= 0) {
            return false;
        }
        $tenantIds = array_values(array_unique(array_map('intval', $tenantIds)));
        $tenantIds = array_values(array_filter($tenantIds, static fn ($id) => $id > 0));
        if (!$tenantIds) {
            $result = DB::delete('delete from user_custom_field_values where user_id = ?', (string) $userId);
            return $result !== false;
        }
        $result = DB::delete(
            'delete ucfv from user_custom_field_values ucfv ' .
            'join tenant_custom_field_definitions d on d.id = ucfv.definition_id ' .
            'where ucfv.user_id = ? and d.tenant_id not in (???)',
            (string) $userId,
            $tenantIds
        );
        return $result !== false;
    }
}
