<?php

namespace App\Services;

use App\Mail\ProfessionalPayoutMail;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Http;

class PayoutNotificationService
{
    public function send(Collection $payouts): array
    {
        $failures = [];

        foreach ($payouts as $payout) {
            $this->sendPush($payout);
            $email = $payout->professional?->user?->email;
            $name = $payout->professional?->user?->profile?->first_name
                ?: $payout->professional?->user?->profile?->full_name
                ?: 'Professional';

            if (! $email) {
                $failures[] = $name.' (no email address)';

                continue;
            }

            try {
                $sentMessage = Mail::to($email, $name)->send(new ProfessionalPayoutMail($payout, $name));

                Log::info('Professional payout email accepted by mail transport.', [
                    'payout_id' => $payout->getKey(),
                    'payout_reference' => $payout->reference,
                    'recipient_domain' => str($email)->after('@')->lower()->toString(),
                    'message_id' => $sentMessage?->getMessageId(),
                ]);
            } catch (\Throwable $exception) {
                Log::error('Professional payout email delivery failed.', [
                    'payout_id' => $payout->getKey(),
                    'payout_reference' => $payout->reference,
                    'recipient_domain' => str($email)->after('@')->lower()->toString(),
                    'exception' => $exception,
                ]);
                $failures[] = $name;
            }

        }

        return $failures;
    }

    private function sendPush($payout): void
    {
        try {
            $key = (string) config('admin.internal_api_key');
            if ($key === '') {
                throw new \RuntimeException('DESXPERT_INTERNAL_API_KEY is not configured.');
            }
            $response = Http::withHeaders(['X-Desxpert-Internal-Key' => $key])
                ->acceptJson()
                ->post(rtrim(config('admin.api_url'), '/').'/api/v1/internal/payout-disbursed', [
                    'payout_id' => $payout->getKey(),
                ]);
            if ($response->failed()) {
                throw new \RuntimeException("API returned HTTP {$response->status()}.");
            }
        } catch (\Throwable $exception) {
            Log::warning('Professional payout push notification failed.', [
                'payout_id' => $payout->getKey(),
                'error' => $exception->getMessage(),
            ]);
        }
    }
}
