<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\LookupInnRequest;
use App\Http\Requests\UpdateRequisitesRequest;
use App\Http\Resources\RequisitesResource;
use App\Models\TenantRequisites;
use App\Services\DaData\PartyLookup;
use App\Services\Requisites\RequisitesService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TenantRequisitesController extends Controller
{
    public function __construct(
        private readonly RequisitesService $service,
        private readonly PartyLookup $party,
    ) {}

    /** GET /api/tenant/requisites */
    public function show(Request $request): JsonResponse
    {
        $req = TenantRequisites::where('tenant_id', $request->user()->tenant_id)->first();

        return response()->json(['data' => $req ? new RequisitesResource($req) : null]);
    }

    /** PUT /api/tenant/requisites */
    public function update(UpdateRequisitesRequest $request): JsonResponse
    {
        $req = $this->service->upsert($request->user()->tenant, $request->validated());

        return response()->json(['data' => new RequisitesResource($req)]);
    }

    /** POST /api/tenant/requisites/lookup-inn — мягкая подтяжка, ничего не сохраняет */
    public function lookupInn(LookupInnRequest $request): JsonResponse
    {
        $res = $this->party->findByInn($request->validated()['inn']);
        if ($res === null) {
            return response()->json(['found' => false]);
        }

        return response()->json([
            'found' => true,
            'legal_name' => $res->legalName,
            'kpp' => $res->kpp,
            'ogrn' => $res->ogrn,
            'legal_address' => $res->address,
            'subject_type_hint' => $res->type === 'INDIVIDUAL' ? 'sole_proprietor' : 'legal_entity',
        ]);
    }
}
