<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\CrmUserManager;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\Services\CurrentUserPayloadBuilder;
use WP_REST_Request;

/**
 * Current-user profile picture management.
 *
 * POST   /wp-json/plover-crm/v1/access-avatar
 * DELETE /wp-json/plover-crm/v1/access-avatar
 */
class AccessAvatarEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/access-avatar';
    }

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

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

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

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

    private function uploadAvatar(WP_REST_Request $request)
    {
        $profile = CrmUserManager::getCurrentProfile();

        if (!$profile) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $files = $request->get_file_params();
        $avatarFile = $files[CrmUserManager::AVATAR_UPLOAD_FIELD]
            ?? ($_FILES[CrmUserManager::AVATAR_UPLOAD_FIELD] ?? null);

        if (!$avatarFile) {
            return $this->error('Choose an image to upload.', 400, 'avatar_missing');
        }

        $updatedProfile = CrmUserManager::replaceAvatarForPublicUser((int) $profile['id'], $avatarFile);

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

        return $this->success([
            'user' => CurrentUserPayloadBuilder::build(),
            'message' => 'Profile picture updated successfully.',
        ], ['updated' => true]);
    }

    private function removeAvatar()
    {
        $profile = CrmUserManager::getCurrentProfile();

        if (!$profile) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        if (!CrmUserManager::removeAvatarForPublicUser((int) $profile['id'])) {
            return $this->error('Unable to remove the current profile picture.', 500, 'avatar_remove_failed');
        }

        return $this->success([
            'user' => CurrentUserPayloadBuilder::build(),
            'message' => 'Profile picture removed successfully.',
        ], ['updated' => true]);
    }

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

        if ($errorCode === 'user_not_found') {
            return 404;
        }

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

        return 500;
    }
}
