<?php

namespace App\Services;

use App\Repositories\Member;

class MemberService
{
    const VALID_TYPES_FIRST = 'A';
    const VALID_TYPES_LAST = 'J';

    private Member $memberRepository;
    private array $validTypes;

    public function __construct(Member $memberRepository)
    {
        $this->memberRepository = $memberRepository;
        $this->validTypes = range(self::VALID_TYPES_FIRST, self::VALID_TYPES_LAST);
    }

    public function save(array $data)
    {
        if (isset($data['id'])) {
            $member = $this->memberRepository->findOrFail($data['id']);
            $member->update($data);
        } else {
            $member = $this->memberRepository->create($data);
        }

        return $member;
    }

    public function seed(array $data)
    {
        $member = $this->memberRepository->create($data);

        return $member;
    }

    public function delete($id, $forceDelete = false)
    {
        $member = $this->memberRepository->withTrashed()->findOrFail($id);

        if ($forceDelete || $member->deleted_at) {
            return $member->forceDelete($id);
        }

        $member->delete();
    }

    public function get($id)
    {
        return $this->memberRepository->findOrFail($id);
    }

    public function getAll()
    {
        return $this->memberRepository->all();
    }

    public function with(array $children)
    {
        return $this->memberRepository->with($children)->get();
    }

    public function getOneWith($id, array $children)
    {
        return $this->memberRepository->with($children)->withTrashed()->findOrFail($id);
    }

    public function countAll()
    {
        // return $this->memberRepository->where('published', true)->get()->count();
        return $this->memberRepository->get()->count();
    }

    public function getValidTypes(): array
    {
        return $this->validTypes;
    }
}
