<?php

namespace App\Services;

use App\Models\Branch;
use App\Repositories\Eloquent\BranchRepository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class BranchService
{
    protected BranchRepository $branchRepository;
    protected LoggingService $loggingService;

    public function __construct(BranchRepository $branchRepository, LoggingService $loggingService)
    {
        $this->branchRepository = $branchRepository;
        $this->loggingService = $loggingService;
    }

    public function getAllBranches(int $perPage = 15): LengthAwarePaginator
    {
        $this->loggingService->logService('BranchService::getAllBranches');

        return $this->branchRepository
            ->with(['parent', 'children'])
            ->orderBy('name')
            ->paginate($perPage);
    }

    public function getActiveBranches(): Collection
    {
        $this->loggingService->logService('BranchService::getActiveBranches');

        return $this->branchRepository->getActiveBranches();
    }

    public function getBranch(int $id): Branch
    {
        $this->loggingService->logService('BranchService::getBranch', ['id' => $id]);

        return $this->branchRepository
            ->with(['parent', 'children'])
            ->findOrFail($id);
    }

    public function createBranch(array $data): Branch
    {
        $this->loggingService->logService('BranchService::createBranch', $data);

        $branch = $this->branchRepository->create($data);

        $this->loggingService->logService('BranchService::createBranch', null, "Branch {$branch->id} created");

        return $branch->load(['parent', 'children']);
    }

    public function updateBranch(int $id, array $data): Branch
    {
        $this->loggingService->logService('BranchService::updateBranch', ['id' => $id, 'data' => $data]);

        $branch = $this->branchRepository->update($id, $data);

        $this->loggingService->logService('BranchService::updateBranch', null, "Branch {$id} updated");

        return $branch->load(['parent', 'children']);
    }

    public function deleteBranch(int $id): bool
    {
        $this->loggingService->logService('BranchService::deleteBranch', ['id' => $id]);

        $result = $this->branchRepository->delete($id);

        $this->loggingService->logService('BranchService::deleteBranch', null, "Branch {$id} deleted");

        return $result;
    }

    public function updateBranchSettings(int $id, array $settings): Branch
    {
        $this->loggingService->logService('BranchService::updateBranchSettings', ['id' => $id, 'settings' => $settings]);

        $branch = $this->branchRepository->updateSettings($id, $settings);

        $this->loggingService->logService('BranchService::updateBranchSettings', null, "Branch {$id} settings updated");

        return $branch;
    }
}
