<?php

namespace App\Services;

use App\Models\IntegrationSetting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\OneCSyncLog;
use Carbon\Carbon;

class OneCService
{
    public function sendCompletedRequest($request): bool
    {
        $settings = IntegrationSetting::oneC();

        if (!$settings || !$settings->enabled || !$settings->url) {
            Log::info('1C integration disabled or missing config');
            return false;
        }

        if ($request->sent_to_1c) {
            Log::info('1C already sent', ['request_id' => $request->id]);
            return true;
        }

        $payload = [
            'external_id' => $request->id,
            'title' => $request->title,
            'client_name' => $request->client_name,
            'phone' => $request->client_phone,
            'address' => $request->address,
            'region' => $request->region,
            'installer' => $request->installer?->name,

            'scheduled_date' => $request->scheduled_date
                ? Carbon::parse($request->scheduled_date)->toISOString()
                : null,

            'completed_at' => $request->completed_at
                ? Carbon::parse($request->completed_at)->toISOString()
                : null,

            'installation_price' => $this->getInstallationPrice($request),
        ];

        $signature = hash_hmac(
            'sha256',
            json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            $settings->token ?? ''
        );

        try {
            $response = Http::timeout(15)
                ->retry(3, 200)
                ->withHeaders([
                    'Authorization' => 'Bearer ' . $settings->token,
                    'Accept' => 'application/json',
                    'X-Signature' => $signature,
                ])
                ->post($settings->url, $payload);

            if (!$response->successful()) {

                OneCSyncLog::create([
                    'request_id' => $request->id,
                    'status' => 'error_http',
                    'response' => $response->body(),
                ]);

                Log::error('1C sync failed', [
                    'request_id' => $request->id,
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return false;
            }

            $request->update([
                'sent_to_1c' => true
            ]);

            OneCSyncLog::create([
                'request_id' => $request->id,
                'status' => 'success',
                'response' => $response->body(),
            ]);

            return true;

        } catch (\Throwable $e) {

            OneCSyncLog::create([
                'request_id' => $request->id,
                'status' => 'error_exception',
                'response' => $e->getMessage(),
            ]);

            Log::error('1C exception', [
                'message' => $e->getMessage(),
                'request_id' => $request->id,
            ]);

            return false;
        }
    }

    private function getInstallationPrice($request): ?float
    {
        return $request->actions()
            ->where('action', 'completed')
            ->latest()
            ->first()?->installation_price;
    }
}
