<?php

namespace PloverCRM\Core\Api\V1;

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

/**
 * Shared business logo management.
 *
 * POST   /wp-json/plover-crm/v1/settings/business-information/logo
 * DELETE /wp-json/plover-crm/v1/settings/business-information/logo
 */
class BusinessInformationLogoEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/settings/business-information/logo';
    }

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

    public function handle(WP_REST_Request $request)
    {
        if ($request->get_method() === 'POST') {
            return $this->uploadLogo($request);
        }

        if ($request->get_method() === 'DELETE') {
            return $this->removeLogo();
        }

        return $this->error('The requested endpoint or method is not valid', 400, 'invalid_request');
    }

    private function uploadLogo(WP_REST_Request $request)
    {
        if (!Permissions::canAccessSetting('business_information', 'manage')) {
            return $this->error(
                'You do not have permission to update business information.',
                403,
                'business_information_update_permission_denied'
            );
        }

        $files = $request->get_file_params();
        $logoFile = $files[BusinessInformationService::LOGO_UPLOAD_FIELD]
            ?? ($_FILES[BusinessInformationService::LOGO_UPLOAD_FIELD] ?? null);

        if (!$logoFile) {
            return $this->error('Choose a logo image to upload.', 400, 'business_logo_missing');
        }

        $updated = BusinessInformationService::replaceLogo($logoFile);

        if (is_wp_error($updated)) {
            return $this->error(
                $updated->get_error_message(),
                $this->resolveErrorStatus($updated->get_error_code()),
                $updated->get_error_code()
            );
        }

        return $this->success([
            'business_information' => $updated,
            'message' => 'Business logo updated successfully.',
        ], ['updated' => true]);
    }

    private function removeLogo()
    {
        if (!Permissions::canAccessSetting('business_information', 'manage')) {
            return $this->error(
                'You do not have permission to update business information.',
                403,
                'business_information_update_permission_denied'
            );
        }

        if (!BusinessInformationService::removeLogo()) {
            return $this->error(
                'Unable to remove the current business logo.',
                500,
                'business_logo_remove_failed'
            );
        }

        return $this->success([
            'business_information' => BusinessInformationService::get(),
            'message' => 'Business logo removed successfully.',
        ], ['updated' => true]);
    }

    private function resolveErrorStatus(string $errorCode): int
    {
        if ($errorCode === 'business_logo_too_large') {
            return 413;
        }

        if (in_array($errorCode, ['business_logo_missing', 'business_logo_upload_failed'], true)) {
            return 400;
        }

        return 500;
    }
}
