<?php
namespace PrimeLink\Modules\Imports\DataSources;

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

final class UrlSource implements DataSourceInterface {

    public function handle( array $payload ) {
        $url = isset( $payload['url'] ) ? esc_url_raw( $payload['url'] ) : '';
        if ( ! $url ) {
            return array( 'error' => 'Missing URL.' );
        }

        $response = \PrimeLink\Helpers\HttpHelper::get( $url, array(
            'timeout'     => 30,
            'retry'       => 1,
            'retry_delay' => 1,
        ) );

        if ( ! $response['success'] ) {
            return array( 'error' => $response['error'] ?? 'Failed to fetch URL.' );
        }

        $body = $response['body'];
        if ( ! $body ) {
            return array( 'error' => 'Empty response.' );
        }

        $upload_dir = wp_upload_dir();
        $dest_dir   = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
        $dest_url   = trailingslashit( $upload_dir['baseurl'] ) . 'primelink/';

        if ( ! \PrimeLink\Helpers\FilesystemHelper::directory_exists( $dest_dir ) ) {
            \PrimeLink\Helpers\FilesystemHelper::create_directory( $dest_dir );
        }

        $ext  = strtolower( pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ) );
        $name = sanitize_file_name( basename( parse_url( $url, PHP_URL_PATH ) ) );
        if ( ! $ext ) { $ext = 'csv'; $name .= '.csv'; }

        $path = $dest_dir . time() . '-' . $name;
        \PrimeLink\Helpers\FilesystemHelper::write_file( $path, $body );

        return array(
            'path'          => $path,
            'url'           => $dest_url . basename( $path ),
            'type'          => $ext,
            'original_name' => $name,
        );
    }
}