<?php

namespace App\Services;

use App\Models\Family;
use App\Repositories\Eloquent\FamilyRepository;
use App\Support\BranchContext;

class FamilyService extends BaseService
{
    public function __construct(protected FamilyRepository $families)
    {
        parent::__construct($families);
    }

    /** Listing query (with student counts) for the index screen. */
    public function listing()
    {
        return $this->families->listing();
    }

    public function create(array $data): Family
    {
        // Resolve the branch this family belongs to, then generate its code.
        $branchId = $data['branch_id'] ?? app(BranchContext::class)->currentId();
        $branchId ??= auth()->user()?->branch_id;

        $data['branch_id'] = $branchId;
        $data['family_code'] = Family::nextCode((int) $branchId);

        return parent::create($data);
    }
}
