<?php

namespace App\Observers;

use App\Models\Branch;
use Illuminate\Support\Facades\DB;

class BranchObserver
{
    /**
     * Handle the Branch "created" event.
     */
    public function created(Branch $branch): void
    {
        $accounts = $branch->client->accounts;
        DB::transaction(function () use ($branch, $accounts) {
            foreach ($accounts as $account) {
                $branch->balances()->updateOrCreate(
                    attributes: [
                        'account_id' => $account->id,
                        'is_starting' => true,
                    ],
                    values: [
                        'balance' => $account->starting_balance,
                    ]);
            }
        }, 2);

    }

    /**
     * Handle the Branch "updated" event.
     */
    public function updated(Branch $branch): void
    {
        //
    }

    /**
     * Handle the Branch "deleted" event.
     */
    public function deleted(Branch $branch): void
    {
        //
    }

    /**
     * Handle the Branch "restored" event.
     */
    public function restored(Branch $branch): void
    {
        //
    }

    /**
     * Handle the Branch "force deleted" event.
     */
    public function forceDeleted(Branch $branch): void
    {
        //
    }
}
