<?php

namespace App\Services;

use App\Models\Branch;
use App\Repositories\Eloquent\BranchRepository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class BranchService extends BaseService
{
    public function __construct(protected BranchRepository $branches)
    {
        parent::__construct($branches);
    }

    /** Query limited to the branches the current user may see. */
    public function accessibleQuery(): Builder
    {
        $query = $this->branches->withCounts();

        $user = Auth::user();
        if ($user && ! $user->isSuperAdmin()) {
            $query->whereIn('id', $user->accessibleBranchIds());
        }

        return $query;
    }

    public function create(array $data): Branch
    {
        $data['logo'] = $this->storeLogo($data);

        /** @var Branch $branch */
        $branch = parent::create($data);

        return $branch;
    }

    public function update(int|string $id, array $data): Branch
    {
        /** @var Branch $branch */
        $branch = $this->findOrFail($id);

        if (! empty($data['logo'])) {
            $this->deleteLogo($branch->logo);
            $data['logo'] = $this->storeLogo($data);
        } else {
            unset($data['logo']);
        }

        return parent::update($id, $data);
    }

    private function storeLogo(array $data): ?string
    {
        $file = $data['logo'] ?? null;
        if ($file && is_object($file) && method_exists($file, 'store')) {
            return $file->store('branches/logos', 'public');
        }

        return null;
    }

    private function deleteLogo(?string $path): void
    {
        if ($path && Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }
    }
}
