<?php

namespace App\Jobs;

use App\Models\ImportBatchRow;
use App\Services\OptumPreServiceEligibilityClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessOptumEligibilityForBatchJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $importBatchId;
    public string $environment;

    public function __construct(int $importBatchId, string $environment = 'sandbox')
    {
        $this->importBatchId = $importBatchId;
        $this->environment = $environment ?: 'sandbox';
    }

    public function handle(OptumPreServiceEligibilityClient $optum): void
    {
        ImportBatchRow::query()
            ->where('import_batch_id', $this->importBatchId)
            ->orderBy('id')
            ->chunkById(100, function ($rows) use ($optum) {
                foreach ($rows as $row) {
                    $data = is_array($row->row_data) ? $row->row_data : (array) $row->row_data;

                    $inputFields = $this->buildInputFields($data);
                    $providerTaxId = (string) ($inputFields['providerTaxId'] ?? $data['providerTaxId'] ?? $data['provider_tax_id'] ?? '999999999');

                    // providerTaxId is a header, not part of EligibilityInput
                    unset($inputFields['providerTaxId'], $inputFields['provider_tax_id']);

                    $result = $optum->checkEligibility(
                        $inputFields,
                        $providerTaxId,
                        $this->environment
                    );

                    $row->forceFill([
                        'request_data' => $result['request'] ?? [],
                        'response_data' => [
                            'ok' => $result['ok'] ?? false,
                            'headers' => $result['headers'] ?? [],
                            'body' => $result['body'] ?? null,
                            'environment' => $this->environment,
                        ],
                    ])->save();
                }
            });
    }

    private function buildInputFields(array $data): array
    {
        // If your sheet has heading row, keys will already be named.
        $hasStringKeys = false;
        foreach (array_keys($data) as $k) {
            if (is_string($k)) {
                $hasStringKeys = true;
                break;
            }
        }

        if ($hasStringKeys) {
            $input = [
                'serviceLevelCodes' => $data['serviceLevelCodes'] ?? $data['service_level_codes'] ?? '001',
                'payerId' => $data['payerId'] ?? $data['payer_id'] ?? null,
                'memberId' => $data['memberId'] ?? $data['member_id'] ?? null,
                'firstName' => $data['firstName'] ?? $data['first_name'] ?? null,
                'lastName' => $data['lastName'] ?? $data['last_name'] ?? null,
                'groupNumber' => $data['groupNumber'] ?? $data['group_number'] ?? null,
                'dateOfBirth' => $data['dateOfBirth'] ?? $data['date_of_birth'] ?? null,
                'serviceStartDate' => $data['serviceStartDate'] ?? $data['service_start_date'] ?? null,
                'serviceEndDate' => $data['serviceEndDate'] ?? $data['service_end_date'] ?? null,
                'trnId' => $data['trnId'] ?? $data['trn_id'] ?? null,
                'providerLastName' => $data['providerLastName'] ?? $data['provider_last_name'] ?? null,
                'providerNPI' => $data['providerNPI'] ?? $data['provider_npi'] ?? null,
                'planStartDate' => $data['planStartDate'] ?? $data['plan_start_date'] ?? null,
                'planEndDate' => $data['planEndDate'] ?? $data['plan_end_date'] ?? null,
                'familyIndicator' => $data['familyIndicator'] ?? $data['family_indicator'] ?? null,
                'providerTaxId' => $data['providerTaxId'] ?? $data['provider_tax_id'] ?? null,
            ];

            return array_filter($input, function ($v) {
                return !is_null($v) && $v !== '';
            });
        }

        // No headings: assume fixed column order (0..)
        $input = [
            'serviceLevelCodes' => $data[0] ?? '001',
            'payerId' => $data[1] ?? null,
            'memberId' => $data[2] ?? null,
            'firstName' => $data[3] ?? null,
            'lastName' => $data[4] ?? null,
            'groupNumber' => $data[5] ?? null,
            'dateOfBirth' => $data[6] ?? null,
            'serviceStartDate' => $data[7] ?? null,
            'serviceEndDate' => $data[8] ?? null,
            'trnId' => $data[9] ?? null,
            'providerLastName' => $data[10] ?? null,
            'providerNPI' => $data[11] ?? null,
            'planStartDate' => $data[12] ?? null,
            'planEndDate' => $data[13] ?? null,
            'familyIndicator' => $data[14] ?? null,
            'providerTaxId' => $data[15] ?? null,
        ];

        return array_filter($input, function ($v) {
            return !is_null($v) && $v !== '';
        });
    }
}

