<?php

namespace Gaco\SnapBi\Support;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Response as ResponseFacade;
use Gaco\SnapBi\Traits\BuildResponseCode;

/**
 * Response Builder for SnapBi
 * 
 * Builds standardized JSON responses for SNAP BI API
 */
class ResponseBuilder
{
    use BuildResponseCode;

    /**
     * Build success response
     * 
     * @param string $serviceCode Service code (e.g., '24' for Inquiry)
     * @param array $data Response data
     * @param array $additionalInfo Additional information
     * @param string $message Response message
     * @return JsonResponse
     */
    public function success(string $serviceCode, array $data = [], array $additionalInfo = [], string $message = 'Successful'): JsonResponse
    {
        $response = [
            'responseCode' => $this->buildCode(200, $serviceCode, 0),
            'responseMessage' => $message,
            ...$data,
        ];

        // Only include additionalInfo if it's not empty
        // If additionalInfo is empty array, it means it wasn't provided or was null/empty
        // Only include it if it has content (was provided in request and != null and != {})
        if (!empty($additionalInfo)) {
            $response['additionalInfo'] = $additionalInfo;
        }

        return ResponseFacade::json($response, 200);
    }

    /**
     * Build error response
     * 
     * Error response format: only responseCode and responseMessage
     * 
     * @param string $serviceCode Service code (e.g., '24' for Inquiry)
     * @param string $message Error message
     * @param int $httpCode HTTP status code (default: 400)
     * @param int $caseCode Case code (default: 0)
     * @param array $errorData Additional error data (not used in response, kept for compatibility)
     * @return JsonResponse
     */
    public function error(string $serviceCode, string $message, int $httpCode = 400, int $caseCode = 0, array $errorData = []): JsonResponse
    {
        // Error response only contains responseCode and responseMessage
        return ResponseFacade::json([
            'responseCode' => $this->buildCode($httpCode, $serviceCode, $caseCode),
            'responseMessage' => $message
        ], $httpCode);
    }
}
