﻿<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class SalaryMarketComparisonService
{
  public function compare(array $payload): array
  {
    $response = Http::withToken(config('services.openai.key'))
      ->post('https://api.openai.com/v1/responses', [
        'prompt' => [
          'id' => 'pmpt_6975d50e65bc819589e36b0174c0c0d80c6334aa7e56ea93',
          // 'version' => '8',
        ],
        'input' => json_encode($payload),
      ]);

    if (!$response->successful()) {
      throw new \RuntimeException(
        'OpenAI error: ' . $response->body()
      );
    }

    /**
     * Responses API returns an array of outputs.
     * We extract the text content.
     */
    $content = collect($response->json('output'))
      ->flatMap(fn($item) => $item['content'] ?? [])
      ->firstWhere('type', 'output_text')['text'] ?? null;

    return json_decode($content, true);
  }