<?php

namespace App\Domain\Identity\Services;

use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Exceptions\DomainException;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class BranchService
{
    public function create(array $data, User $actor): Branch
    {
        return DB::transaction(function () use ($data, $actor) {
            $branch = Branch::create($data);

            // If this is marked as main, unmark others
            if ($branch->is_main) {
                Branch::where('academy_id', $branch->academy_id)
                    ->where('id', '!=', $branch->id)
                    ->update(['is_main' => false]);
            }

            return $branch;
        });
    }

    public function update(Branch $branch, array $data, User $actor): Branch
    {
        return DB::transaction(function () use ($branch, $data) {
            $branch->update($data);

            if (isset($data['is_main']) && $data['is_main']) {
                Branch::where('academy_id', $branch->academy_id)
                    ->where('id', '!=', $branch->id)
                    ->update(['is_main' => false]);
            }

            return $branch->fresh();
        });
    }

    public function delete(Branch $branch): void
    {
        // TODO: in later phases, check for active participants, groups, sessions
        if ($branch->is_main) {
            throw new DomainException(
                __('لا يمكن حذف الفرع الرئيسي')
            );
        }

        $branch->delete();
    }
}
