<?php

namespace PloverCRM\Core\Api\V1;

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

/**
 * Tags Endpoint
 * 
 * GET    /wp-json/plover-crm/v1/tags              - Get all tags
 * POST   /wp-json/plover-crm/v1/tags              - Create new tag
 * PUT    /wp-json/plover-crm/v1/tags/{id}         - Update tag
 * DELETE /wp-json/plover-crm/v1/tags/{id}         - Delete tag
 */
class TagsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/tags(?:/(?P<id>\d+))?';
    }

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

    public function handle(WP_REST_Request $request)
    {
        $crm = $this->container->get('crm');

        if (!$crm->isAvailable()) {
            return $this->error('CRM service is currently unavailable', 503, 'crm_unavailable');
        }

        $method = $request->get_method();
        $id = $request->get_param('id');

        switch ($method) {
            case 'GET':
                return $this->getTags($crm);

            case 'POST':
                return $this->createTag($crm, $request);

            case 'PUT':
                return $this->updateTag($crm, $id, $request);

            case 'DELETE':
                return $this->deleteTag($crm, $id);

            default:
                return $this->error('The requested method is not supported for this endpoint', 405);
        }
    }

    /**
     * Get all tags
     */
    private function getTags($crm)
    {
        // Check read permission for tag definitions
        if (!Permissions::canAccessEntity('tag_definitions', 'read')) {
            return $this->error('You do not have permission to view tags', 403, 'tags_read_permission_denied');
        }

        $tags = $crm->getAllTags();

        return $this->success($tags, [
            'total' => count($tags),
        ]);
    }

    /**
     * Create new tag
     */
    private function createTag($crm, WP_REST_Request $request)
    {
        // Check create permission for tag definitions
        if (!Permissions::canAccessEntity('tag_definitions', 'create')) {
            return $this->error('You do not have permission to create tags', 403, 'tags_create_permission_denied');
        }

        $data = $request->get_json_params();

        if (empty($data['title'])) {
            return $this->error('Tag title is required', 400, 'missing_tag_title');
        }

        $result = $crm->createTag($data);

        if (!$result) {
            return $this->error('Unable to create tag', 500, 'tag_creation_failed');
        }

        return $this->success($result, ['created' => true], 201);
    }

    /**
     * Update tag
     */
    private function updateTag($crm, $id, WP_REST_Request $request)
    {
        // Check update permission for tag definitions
        if (!Permissions::canAccessEntity('tag_definitions', 'update')) {
            return $this->error('You do not have permission to update tags', 403, 'tags_update_permission_denied');
        }

        if (empty($id)) {
            return $this->error('Tag ID is required', 400, 'missing_tag_id');
        }

        $data = $request->get_json_params();

        if (empty($data)) {
            return $this->error('Request body must contain valid tag data', 400, 'invalid_request_body');
        }

        $result = $crm->updateTag(intval($id), $data);

        if (!$result) {
            return $this->error('Unable to update tag', 500, 'tag_update_failed');
        }

        return $this->success($result, ['updated' => true]);
    }

    /**
     * Delete tag
     */
    private function deleteTag($crm, $id)
    {
        // Check delete permission for tag definitions
        if (!Permissions::canAccessEntity('tag_definitions', 'delete')) {
            return $this->error('You do not have permission to delete tags', 403, 'tags_delete_permission_denied');
        }

        if (empty($id)) {
            return $this->error('Tag ID is required', 400, 'missing_tag_id');
        }

        $result = $crm->deleteTag(intval($id));

        if (!$result) {
            return $this->error('Unable to delete tag', 500, 'tag_deletion_failed');
        }

        return $this->success(['deleted' => true]);
    }
}
