<?php

namespace App\Repositories\Eloquent;

use App\Models\Branch;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class BranchRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Branch();
    }

    public function getActiveBranches(): Collection
    {
        return $this->executeWithLogging(__FUNCTION__, function () {
            return $this->model->where('is_active', true)->get();
        });
    }

    public function getRootBranches(): Collection
    {
        return $this->executeWithLogging(__FUNCTION__, function () {
            return $this->model->whereNull('parent_id')->get();
        });
    }

    public function getChildBranches(int $parentId): Collection
    {
        return $this->executeWithLogging(__FUNCTION__, function () use ($parentId) {
            return $this->model->where('parent_id', $parentId)->get();
        });
    }

    public function findByCode(string $code): ?Branch
    {
        return $this->executeWithLogging(__FUNCTION__, function () use ($code) {
            return $this->model->where('code', $code)->first();
        });
    }

    public function updateSettings(int $id, array $settings): Branch
    {
        return $this->executeWithLogging(__FUNCTION__, function () use ($id, $settings) {
            $branch = $this->model->findOrFail($id);
            $currentSettings = $branch->settings ?? [];
            $branch->settings = array_merge($currentSettings, $settings);
            $branch->save();
            return $branch->fresh();
        });
    }
}
