<?php

namespace PloverCRM\Core\Api\V1;

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

/**
 * Lists Endpoint
 * 
 * GET    /wp-json/plover-crm/v1/lists              - Get all lists
 * POST   /wp-json/plover-crm/v1/lists              - Create new list
 * PUT    /wp-json/plover-crm/v1/lists/{id}         - Update list
 * DELETE /wp-json/plover-crm/v1/lists/{id}         - Delete list
 */
class ListsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/lists(?:/(?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->getLists($crm);

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

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

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

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

    /**
     * Get all lists
     */
    private function getLists($crm)
    {
        // Check read permission for list definitions
        if (!Permissions::canAccessEntity('list_definitions', 'read')) {
            return $this->error('You do not have permission to view lists', 403, 'lists_read_permission_denied');
        }

        $lists = $crm->getAllLists();

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

    /**
     * Create new list
     */
    private function createList($crm, WP_REST_Request $request)
    {
        // Check create permission for list definitions
        if (!Permissions::canAccessEntity('list_definitions', 'create')) {
            return $this->error('You do not have permission to create lists', 403, 'lists_create_permission_denied');
        }

        $data = $request->get_json_params();

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

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

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

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

    /**
     * Update list
     */
    private function updateList($crm, $id, WP_REST_Request $request)
    {
        // Check update permission for list definitions
        if (!Permissions::canAccessEntity('list_definitions', 'update')) {
            return $this->error('You do not have permission to update lists', 403, 'lists_update_permission_denied');
        }

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

        $data = $request->get_json_params();

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

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

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

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

    /**
     * Delete list
     */
    private function deleteList($crm, $id)
    {
        // Check delete permission for list definitions
        if (!Permissions::canAccessEntity('list_definitions', 'delete')) {
            return $this->error('You do not have permission to delete lists', 403, 'lists_delete_permission_denied');
        }

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

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

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

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