<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use App\Services\OptumPreServiceEligibilityClient;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

class PreClaimBatchRowsImport implements ToCollection, WithChunkReading, WithHeadingRow
{
    private int $importBatchId;

    public function __construct(int $importBatchId)
    {
        // Keep Excel header names as-is (e.g. memberId), so you can do $row['memberId']
        HeadingRowFormatter::default('none');
        $this->importBatchId = $importBatchId;
    }

    public function collection(Collection $rows)
    {
        if ($rows->isEmpty()) {
            return;
        }

        /** @var OptumPreServiceEligibilityClient $optum */
        $optum = app(OptumPreServiceEligibilityClient::class);
        $environment = (string) config('optum.environment', 'sandbox');

        $now = now();
        $inserts = [];

        foreach ($rows as $row) {
            $rowArray = is_array($row) ? $row : $row->toArray();
            $inputFields = $this->buildInputFields($rowArray);
            $providerTaxId = (string) ($inputFields['providerTaxId'] ?? $rowArray['providerTaxId'] ?? $rowArray['provider_tax_id'] ?? '999999999');
            //Log::info('TAX ID:', $providerTaxId);
            unset($inputFields['providerTaxId'], $inputFields['provider_tax_id']);

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

            $inserts[] = [
                'import_batch_id' => $this->importBatchId,
                'request_data' => json_encode($result['request'] ?? []),
                'response_data' => json_encode([
                    'ok' => $result['ok'] ?? false,
                    'headers' => $result['headers'] ?? [],
                    'body' => $result['body'] ?? null,
                    'environment' => $environment,
                ]),
                'row_data' => json_encode($rowArray),
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        //DB::table('import_batch_rows')->insert($inserts);
    }

    public function chunkSize(): int
    {
        return 1000;
    }

    public function headingRow(): int
    {
        return 1;
    }

    private function buildInputFields(array $data): array
    {
        $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,
                'dateOfBirth' => $data['dateOfBirth'] ?? $data['date_of_birth'] ?? null,
                'serviceStartDate' => $data['serviceStartDate'] ?? $data['service_start_date'] ?? null,
                'trnId' => $data['trnId'] ?? $data['trn_id'] ?? null,
                'providerLastName' => $data['providerLastName'] ?? $data['provider_last_name'] ?? null,
            ];

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

        /*$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 !== '';
        });*/
    }
}

