<?php

namespace App\Services;

use App\Models\MainAccount;
use Illuminate\Support\Facades\Schema;

class MainAccountPickerService
{
    /**
     * @return array<int, array{id:int,label:string,type:string,sub_table:string|null}>
     */
    public function resolve(int $mainAccountId): array
    {
        $relations = [];

        foreach (['subAccounts', 'subAccounts2', 'subAccounts3', 'subAccounts4', 'subAccounts5'] as $relationName) {
            $tableName = match ($relationName) {
                'subAccounts' => 'sub_accounts',
                'subAccounts2' => 'sub_accounts_2',
                'subAccounts3' => 'sub_accounts_3',
                'subAccounts4' => 'sub_accounts_4',
                'subAccounts5' => 'sub_accounts_5',
            };

            if (Schema::hasTable($tableName)) {
                $relations[] = $relationName;
            }
        }

        $account = MainAccount::with($relations)->findOrFail($mainAccountId);

        $all = $account->allSubAccounts();

        if ($all->isEmpty()) {
            return [[
                'id' => $account->id,
                'label' => "[{$account->account_code}] {$account->account_name}",
                'type' => 'main_account',
                'sub_table' => null,
            ]];
        }

        return $all->map(fn ($sub) => [
            'id' => $sub->id,
            'label' => "[{$sub->account_code}] {$sub->sub_name}",
            'type' => 'sub',
            'sub_table' => $sub->sub_table,
        ])->values()->all();
    }

    public function allMainAccounts()
    {
        $relations = [];

        foreach (['subAccounts', 'subAccounts2', 'subAccounts3', 'subAccounts4', 'subAccounts5'] as $relationName) {
            $tableName = match ($relationName) {
                'subAccounts' => 'sub_accounts',
                'subAccounts2' => 'sub_accounts_2',
                'subAccounts3' => 'sub_accounts_3',
                'subAccounts4' => 'sub_accounts_4',
                'subAccounts5' => 'sub_accounts_5',
            };

            if (Schema::hasTable($tableName)) {
                $relations[] = $relationName;
            }
        }

        return MainAccount::with($relations)->orderBy('account_code')->get()->map(function ($account) {
            $flatSubAccounts = $account->allSubAccounts();
            $account->setRelation('subAccounts', $flatSubAccounts);
            $account->has_subs = $flatSubAccounts->isNotEmpty();

            return $account;
        });
    }
}
