<?php

namespace PloverCRM\Modules\Integrations\Services;

use PloverCRM\Core\Services\SystemFieldRegistry;

class CrmFieldMappingBuilder
{
    public static function build(object $crm): array
    {
        $standardFields = $crm->getStandardFields();
        $customFields = $crm->getAllCustomFields();
        $uniqueFieldInfo = $crm->getRequiredUniqueField();
        $crmFields = [];

        $crmFields[] = [
            'key' => 'full_name',
            'label' => 'Full Name',
            'type' => 'text',
            'group' => 'standard',
            'required' => false,
        ];

        foreach ($standardFields as $key => $label) {
            $crmFields[] = [
                'key' => $key,
                'label' => $label,
                'type' => $key === 'email' ? 'email' : 'text',
                'group' => 'standard',
                'required' => $key === ($uniqueFieldInfo['field'] ?? '') && empty($uniqueFieldInfo['is_custom_field']),
            ];
        }

        foreach ($customFields as $field) {
            $slug = (string) ($field['slug'] ?? '');

            if (!SystemFieldRegistry::isVisibleInIntegrationMapping($slug)) {
                continue;
            }

            $crmFields[] = [
                'key' => 'cf_' . $slug,
                'label' => (string) ($field['label'] ?? $slug),
                'type' => (string) ($field['type'] ?? 'text'),
                'group' => 'custom',
                'required' => $slug === ($uniqueFieldInfo['field'] ?? '') && !empty($uniqueFieldInfo['is_custom_field']),
            ];
        }

        return [
            'crmFields' => $crmFields,
            'requiredUniqueField' => [
                'key' => !empty($uniqueFieldInfo['is_custom_field'])
                    ? 'cf_' . (string) ($uniqueFieldInfo['field'] ?? '')
                    : (string) ($uniqueFieldInfo['field'] ?? ''),
                'label' => (string) ($uniqueFieldInfo['label'] ?? ''),
                'isCustomField' => !empty($uniqueFieldInfo['is_custom_field']),
            ],
        ];
    }
}
