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

use WP_Error;

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

final class DropboxSource implements DataSourceInterface {

    private $settings = array();

    public function __construct( array $settings = array() ) {
        $this->settings = $settings;
    }

    public function handle( array $payload ) {
        $token = $this->settings['dropbox_access_token'] ?? '';
        if ( ! $token ) {
            return array( 'error' => 'Dropbox access token is missing. Add it in Settings → Integrations.' );
        }

        $path = isset( $payload['path'] ) ? trim( (string) $payload['path'] ) : '';
        if ( ! $path && ! empty( $this->settings['dropbox_default_path'] ) ) {
            $path = trim( (string) $this->settings['dropbox_default_path'] );
        }
        if ( ! $path ) {
            return array( 'error' => 'No Dropbox path or shared link provided.' );
        }

        $is_url   = filter_var( $path, FILTER_VALIDATE_URL );
        $endpoint = $is_url ? 'https://content.dropboxapi.com/2/sharing/get_shared_link_file' : 'https://content.dropboxapi.com/2/files/download';
        $arg      = $is_url ? array( 'url' => $path ) : array( 'path' => ( 0 === strpos( $path, '/' ) ? $path : '/' . $path ) );

        $response = \PrimeLink\Helpers\HttpHelper::post( $endpoint, array(
            'headers' => array(
                'Authorization'    => 'Bearer ' . $token,
                'Dropbox-API-Arg'  => wp_json_encode( $arg ),
            ),
            'timeout'     => 45,
            'retry'       => 1,
            'retry_delay' => 1,
        ) );

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

        $code = $response['code'];
        if ( $code < 200 || $code > 299 ) {
            $body = $response['body'];
            return array( 'error' => 'Dropbox download failed (' . $code . '): ' . ( $body ? wp_strip_all_tags( $body ) : 'Unknown error' ) );
        }

        $body = $response['body'];
        if ( ! $body ) {
            return array( 'error' => 'Dropbox returned an empty file.' );
        }

        $meta_header = isset( $response['headers']['dropbox-api-result'] ) ? $response['headers']['dropbox-api-result'] : null;
        $meta        = $meta_header ? json_decode( $meta_header, true ) : array();
        $name        = $meta['name'] ?? basename( $path );
        $name        = sanitize_file_name( $name );

        $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
        if ( ! $ext ) {
            $ext = 'csv';
            $name .= '.csv';
        }

        $type_map = array(
            'xml'  => 'xml',
            'csv'  => 'csv',
            'xlsx' => 'xlsx',
            'xls'  => 'xlsx',
            'json' => 'json',
        );
        $type = $type_map[ $ext ] ?? 'csv';

        $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 );
        }

        $dest_name = time() . '-' . $name;
        $dest_path = $dest_dir . $dest_name;

        \PrimeLink\Helpers\FilesystemHelper::write_file( $dest_path, $body );

        return array(
            'path'          => $dest_path,
            'url'           => $dest_url . $dest_name,
            'type'          => $type,
            'original_name' => $name,
            'source'        => 'dropbox',
            'downloaded_at' => current_time( 'mysql' ),
        );
    }
}
