<?php

namespace App\Modules\Exports\Support;

use RuntimeException;

final class CsvStreamWriter
{
    /** @var resource|null */
    private $handle = null;

    public function __construct(
        private readonly string $absolutePath,
    ) {}

    public function open(): void
    {
        $dir = dirname($this->absolutePath);
        if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) {
            throw new RuntimeException('Cannot create export directory.');
        }
        $h = fopen($this->absolutePath, 'wb');
        if ($h === false) {
            throw new RuntimeException('Cannot open export file for writing.');
        }
        $this->handle = $h;
    }

    /**
     * @param  list<string|int|float|bool|null>  $row
     */
    public function writeRow(array $row): void
    {
        if ($this->handle === null) {
            throw new RuntimeException('CSV writer not open.');
        }
        fputcsv($this->handle, array_map(fn ($v) => $v === null ? '' : (string) $v, $row));
    }

    public function close(): void
    {
        if (is_resource($this->handle)) {
            fclose($this->handle);
        }
        $this->handle = null;
    }
}
