<?php
declare(strict_types=1);

namespace Tests\Factories;

use App\Core\Database;

abstract class Factory
{
    protected Database $db;
    protected array $overrides = [];

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    abstract protected function defaults(): array;

    abstract protected function table(): string;

    public function withOverrides(array $data): static
    {
        $clone = clone $this;
        $clone->overrides = array_merge($clone->overrides, $data);
        return $clone;
    }

    public function make(): array
    {
        return array_merge($this->defaults(), $this->overrides);
    }

    public function create(): array
    {
        $data = $this->make();
        $id = $this->db->insert($this->table(), $data);
        return array_merge($data, ['id' => $id]);
    }

    public function createMany(int $count): array
    {
        $records = [];
        for ($i = 0; $i < $count; $i++) {
            $records[] = $this->create();
        }
        return $records;
    }
}
