<?php

declare(strict_types=1);

namespace App\Services\Requisites;

use App\Models\Tenant;
use App\Models\TenantRequisites;
use App\Support\PhoneNormalizer;

final class RequisitesService
{
    /**
     * @param  array<string,mixed>  $data  валидированный payload (телефон ещё в сыром виде)
     */
    public function upsert(Tenant $tenant, array $data): TenantRequisites
    {
        if (isset($data['contact_phone'])) {
            $data['contact_phone'] = PhoneNormalizer::normalize((string) $data['contact_phone']);
        }

        $req = TenantRequisites::firstOrNew(['tenant_id' => $tenant->id]);
        $req->fill($data);
        $req->tenant_id = $tenant->id;
        $req->requisites_completed_at = filled($req->bank_account) ? now() : null;
        $req->save();

        return $req;
    }

    public function isLightComplete(Tenant $tenant): bool
    {
        $r = TenantRequisites::where('tenant_id', $tenant->id)->first();
        if ($r === null) {
            return false;
        }
        if (blank($r->subject_type) || blank($r->contact_name) || blank($r->contact_phone)) {
            return false;
        }
        if (in_array($r->subject_type, ['legal_entity', 'sole_proprietor'], true) && blank($r->inn)) {
            return false;
        }

        return true;
    }
}
