<?php

namespace Licenzo\Http\Controller\Api\V1;

use Licenzo\Framework\Http\Request;
use Licenzo\Http\Traits\HandlesErrors;
use Licenzo\Services\DataPortService;

if (!defined('ABSPATH')) {
    exit;
}

class DataPortController
{
    use HandlesErrors;

    public function categories()
    {
        try {
            return $this->successResponse(
                (new DataPortService())->categories()
            );
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Failed to load categories');
        }
    }

    public function export(Request $request)
    {
        try {
            $categories = $request->getSafe([
                'categories' => 'sanitize_text_field',
            ]);

            $selected = [];
            if (!empty($categories['categories'])) {
                $selected = array_map('trim', explode(',', $categories['categories']));
            }

            return $this->successResponse(
                (new DataPortService())->export($selected)
            );
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Export failed');
        }
    }

    public function upload(Request $request)
    {
        try {
            $file = $request->file('chunk');

            if (!$file) {
                return $this->validationError([], 'No file chunk uploaded');
            }

            $chunkIndex  = (int) $request->get('chunk_index', 0);
            $totalChunks = (int) $request->get('total_chunks', 1);
            $token       = $request->get('token', null);

            if ($token) {
                $token = sanitize_text_field($token);
            }

            $result = (new DataPortService())->handleChunkUpload($file, $chunkIndex, $totalChunks, $token);

            return $this->successResponse($result);
        } catch (\InvalidArgumentException $e) {
            return $this->validationError([], $e->getMessage());
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Upload failed');
        }
    }

    public function process(Request $request)
    {
        try {
            $token = sanitize_text_field($request->get('token', ''));

            if (empty($token)) {
                return $this->validationError([], 'Missing import token');
            }

            $result = (new DataPortService())->processNextBatch($token);

            return $this->successResponse($result);
        } catch (\InvalidArgumentException $e) {
            return $this->validationError([], $e->getMessage());
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Import processing failed');
        }
    }
}
