<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\Permissions;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\Services\CustomFieldSettingsService;
use WP_REST_Request;

/**
 * Custom field settings endpoint for the standalone app.
 *
 * GET    /wp-json/plover-crm/v1/settings/custom-fields
 * POST   /wp-json/plover-crm/v1/settings/custom-fields
 * PUT    /wp-json/plover-crm/v1/settings/custom-fields
 * DELETE /wp-json/plover-crm/v1/settings/custom-fields
 */
class CustomFieldSettingsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/settings/custom-fields';
    }

    public function getMethod()
    {
        return ['GET', 'POST', 'PUT', 'DELETE'];
    }

    public function handle(WP_REST_Request $request)
    {
        $service = new CustomFieldSettingsService();
        $method = $request->get_method();

        if ($method === 'GET') {
            if (!Permissions::canAccessSetting('custom_fields', 'view')) {
                return $this->error(
                    'You do not have permission to view custom fields.',
                    403,
                    'custom_fields_read_permission_denied'
                );
            }

            return $this->success($service->buildPayload());
        }

        if (!Permissions::canAccessSetting('custom_fields', 'manage')) {
            return $this->error(
                'You do not have permission to manage custom fields.',
                403,
                'custom_fields_manage_permission_denied'
            );
        }

        $payload = $request->get_json_params();
        if (!is_array($payload)) {
            return $this->error(
                'Custom field payload must be a JSON object.',
                422,
                'custom_fields_invalid_payload'
            );
        }

        if ($method === 'POST') {
            $result = $service->createField((array) ($payload['field'] ?? []));
        } elseif ($method === 'PUT') {
            if (isset($payload['order']) && is_array($payload['order'])) {
                $result = $service->reorderFields($payload['order']);
            } else {
                $slug = sanitize_key((string) ($payload['slug'] ?? ''));
                $result = $service->updateField($slug, (array) ($payload['field'] ?? []));
            }
        } else {
            $slug = sanitize_key((string) ($payload['slug'] ?? ''));
            $result = $service->deleteField($slug);
        }

        if (empty($result['success'])) {
            return $this->error(
                (string) ($result['message'] ?? 'Unable to process the custom field request.'),
                (int) ($result['status'] ?? 400),
                'custom_fields_request_failed'
            );
        }

        return $this->success(
            $result['payload'] ?? $service->buildPayload(),
            ['message' => (string) ($result['message'] ?? '')]
        );
    }
}
