<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\ApiClient;

class SendSqliteFile extends Command
{
    protected $signature = 'sqlite:send
            {filename : The sqlite filename (e.g. tempUser.sqlite)}
            {--url=https://ktvcentral.test/api/upload-sqlite : Target full API URL}
            {--token= : Optional Bearer Token}
            {--param=* : Optional extra POST data in key=value format (e.g. user_id=123)}';

    protected $description = 'Send a sqlite file to remote server with optional token and data';

    public function handle(): int
    {
        $filename = $this->argument('filename');
        $url = $this->option('url');
        $token = $this->option('token');
        $params = $this->option('param'); // key=value

        $filePath = storage_path("app/database/{$filename}");

        if (!file_exists($filePath)) {
            $this->error("❌ 檔案不存在: {$filePath}");
            return 1;
        }

        $endpoint = parse_url($url, PHP_URL_PATH);
        $baseUrl = str_replace($endpoint, '', $url);

        // 處理額外參數
        $data = [];
        foreach ($params as $pair) {
            if (str_contains($pair, '=')) {
                [$key, $value] = explode('=', $pair, 2);
                $data[$key] = $value;
            }
        }

        $this->info("📤 傳送檔案 {$filename} 到 {$url} 中...");

        try {
            $client = new ApiClient( $baseUrl ,$token);
            $response = $client->upload($endpoint, ['file' => $filePath], $data);

            if ($response->successful()) {
                $this->info("✅ 傳送成功！");
                $this->info("🔁 回應內容: " . $response->body());
            } else {
                $this->error("❌ 傳送失敗：HTTP {$response->status()}");
                $this->error($response->body());
            }
        } catch (\Exception $e) {
            $this->error("❌ 發生錯誤：" . $e->getMessage());
            return 1;
        }

        return 0;
    }
}

/**
  php artisan sqlite:send tempUser.sqlite \
    --url=https://ktvcentral.test/api/upload-sqlite \
    --token=abc123 \
    --param=user_id=888 --param=env=prod
 */