<?php

/**
 * Migrate Controller
 *
 * This file is used to register all actions for the Category Controller.
 *
 * @since 1.0.0
 */

namespace LinkFiliate\App\Controllers;

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

use LinkFiliate\App\Services\ImportService;
use LinkFiliate\App\Models\Scanner;

class Migrate
{
    protected ImportService $service;

    public function __construct()
    {
        $this->service = new ImportService();
    }

    public function scan(\WP_REST_Request $request)
    {
        $source = sanitize_text_field($request->get_param('source'));

        if (empty($source)) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Missing or invalid source parameter.',
            ], 400);
        }

        $scanner = new Scanner();
        $data = $scanner->scan($source);

        if (isset($data['error'])) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => $data['error'],
            ], 400);
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'data'   => $data,
        ], 200);
    }



    public function import(\WP_REST_Request $request): \WP_REST_Response
    {
        $source = sanitize_text_field($request->get_param('source'));
        if (empty($source)) {
            return new \WP_REST_Response(['status' => 'error', 'message' => 'Missing source'], 400);
        }

        $params = $request->get_json_params();

        // $options = [
        //     'categories'        => !empty($params['importCategories']) && $params['importCategories'] === true,
        //     'click_stats'       => !empty($params['importClickStats']) && $params['importClickStats'] === true,
        //     'duplicateHandling' => $params['duplicateHandling'] ?? 'skip',
        //     'limit'             => intval($params['limit'] ?? 100),
        //     'offset'            => intval($params['offset'] ?? 0),
        // ];

        $options = [
            'categories'        => !empty($params['categories']) && $params['categories'] === true,
            'click_stats'       => !empty($params['click_stats']) && $params['click_stats'] === true,
            'duplicateHandling' => $params['duplicateHandling'] ?? 'skip',
            'limit'             => intval($params['limit'] ?? 100),
            'offset'            => intval($params['offset'] ?? 0),
        ];

        $importer = $this->service->getImporter($source);

        if (!$importer) {
            return new \WP_REST_Response(['status' => 'error', 'message' => "Unknown source {$source}"], 400);
        }

        $data = $importer->import($options);

        return new \WP_REST_Response(['status' => 'success', 'data' => $data], 200);
    }
}
