<?php

namespace App\Services;

use App\Models\Companies\Company;
use Exception;
use Illuminate\Support\Facades\Storage;
use MoveMoveIo\DaData\Enums\BranchType;
use MoveMoveIo\DaData\Enums\CompanyType as DaDataCompanyType;
use MoveMoveIo\DaData\Facades\DaDataCompany;

class DaDataService {
    public string $inn;
    public ?string $kpp;

    public function __construct($inn, $kpp = null) {
        $this->inn = $inn;
        $this->kpp = $kpp;
    }

    public function saveToCompany(Company $company): Company {
        if ($result = $this->getCompanyData()) {
            if (!empty($result['company'])) $company->update($result['company']);
            if (!empty($result['address'])) {
                $company->legalAddress->update($result['address']);
                $company->actualAddress->update($result['address']);
            }
        }
        return $company;
    }

    public function getCompanyData() {
        $result = [];
        $data = $this->getSavedResponse();
        if (!$data && is_numeric($this->inn)) {
            try {
                $data = DaDataCompany::id($this->inn, 1, $this->kpp, BranchType::MAIN, DaDataCompanyType::LEGAL);
                $this->saveResponse($data);
            } catch (Exception $exception) {
                echo 'INN: ' . $this->inn . ' error: ' . $exception->getMessage() . "\n";
                return false;
            }
        }
        if ($data && is_array($data) && !empty($data['suggestions'])) {
            $data = $data['suggestions'];
            if (!empty($data[0])) $data = $data[0];
            $data = $data['data'];

            $result['company'] = [
                'name' => $data['name']['short_with_opf'] ?? null,
                'full_name' => $data['name']['full_with_opf'] ?? null,
                'kpp' => $data['kpp'] ?? null,
                'ogrn' => $data['ogrn'] ?? null,
                'okpo' => $data['okpo'] ?? null,
                'okved' => $data['okved'] ?? null
            ];

            $result['address'] = [
                'full' => $data['address']['unrestricted_value'] ?? null,
                'postcode' => $data['address']['data']['postal_code'] ?? null,
                'country' => $data['address']['data']['country'] ?? null,
                'region' => $data['address']['data']['region'] ?? null,
                'city' => $data['address']['data']['city'] ?? null,
                'district' => $data['address']['data']['federal_district'] ?? null,
                'street' => $data['address']['data']['street_with_type'] ?? null,
                'house' => "{$data['address']['data']['house_type_full']} {$data['address']['data']['house']}",
                'block' => "{$data['address']['data']['block_type_full']} {$data['address']['data']['block']}",
                'office' => "{$data['address']['data']['flat_type_full']} {$data['address']['data']['flat']}"
            ];
        }
        return $result;
    }

    public function saveResponse($data) {
        Storage::put($this->makePath(), collect($data)->toJson());
    }

    public function getSavedResponse() {
        $path = $this->makePath();
        return Storage::exists($path) ? json_decode(Storage::get("dadata/{$this->inn}.json"), true) : null;
    }

    public function makePath(): string {
        return "dadata/{$this->inn}.json";
    }

}