<?php

namespace App\Repositories;

use App\Models\Contract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ContractRepository extends BaseRepository
{
    public function __construct(Contract $model)
    {
        parent::__construct($model);
    }

    public function create(array $attributes): Model
    {
        return DB::transaction(function () use ($attributes) {
            $dependents = $attributes['dependents'] ?? [];
            unset($attributes['dependents']);

            $contract = parent::create($attributes);

            $this->syncDependents($contract, $dependents);

            return $contract;
        });
    }

    public function update(Model $model, array $attributes): bool
    {
        return DB::transaction(function () use ($model, $attributes) {
            $dependents = $attributes['dependents'] ?? [];
            unset($attributes['dependents']);

            $result = parent::update($model, $attributes);

            $this->syncDependents($model, $dependents);

            return $result;
        });
    }

    /**
     * Sync dependents: delete old, create new non-empty ones
     */
    protected function syncDependents(Model $contract, array $dependents): void
    {
        $contract->dependents()->delete();

        foreach ($dependents as $dependent) {
            if (!empty($dependent['name'])) {
                $contract->dependents()->create($dependent);
            }
        }
    }
}
