<?php

namespace Myvetshop\Module\Clinique\Import\Kalivet\ImportFile;

class ImportDispatcher
{
    public const DISPATCH_FOLDER_NAME = 'kalivet_dispatched';

    protected string $dispatchFolder;

    protected static function delTree(string $dir): bool
    {
        $files = \array_diff(\scandir($dir) ?: [], ['.', '..']);

        foreach ($files as $file) {
            \is_dir("$dir/$file") ? self::delTree("$dir/$file") : \unlink("$dir/$file");
        }

        return \rmdir($dir);
    }

    public function __construct()
    {
        $this->dispatchFolder = sys_get_temp_dir() . DIRECTORY_SEPARATOR . self::DISPATCH_FOLDER_NAME . DIRECTORY_SEPARATOR;

        if (!\file_exists($this->dispatchFolder)) {
            \mkdir($this->dispatchFolder, 0777, true);
        }
    }

    /**
     * @param array<mixed> $line
     */
    public function dispatchLine(string $section, array $line): void
    {
        switch ($section) {
            case 'STORES':
                $fileName = $line['id_veto_alcyon'] . '.json';
                if (!\is_file($this->dispatchFolder . $fileName)) {
                    \file_put_contents($this->dispatchFolder . $fileName, \json_encode($line));
                }

                return;

            case 'CUSTOMERS':
                $id = $line['id_customer'] ?? null;
                break;

            case 'ADDRESSES':
                $id = $line['id_address'] ?? null;
                break;

            case 'ORDERS':
                $id = $line['id_order'] ?? null;
                break;

            case 'ORDER_DETAILS':
            case 'ORDER_DETAIL_TAXES':
                $id = $line['id_order_detail'] ?? null;
                break;

            case 'CART_PRODUCTS':
                $id = ($line['id_cart'] ?? '')
                    . '-' . ($line['id_product'] ?? '')
                    . '-' . ($line['id_product_attribute'] ?? '');
                break;

            case 'REWARDS':
                $id = 'reward';
                break;

            default:
                return;
        }

        $email = $line['email'] ?? null;

        if (!$email || !$id) {
            throw new \Exception("Can't dispatch line : " . \json_encode($line));
        }

        $outputDir = $this->dispatchFolder
            . \str_replace('@', '_AT_', \strval($email)) . DIRECTORY_SEPARATOR
            . $section . DIRECTORY_SEPARATOR;

        if (!\file_exists($outputDir)) {
            \mkdir($outputDir, 0777, true);
        }

        $fileName = $id . '.json';
        if (!\is_file($outputDir . $fileName)) {
            \file_put_contents($outputDir . $fileName, \json_encode($line));
        }
    }

    public function clearAll(): void
    {
        if (\file_exists($this->dispatchFolder)) {
            self::delTree($this->dispatchFolder);
        }
        \mkdir($this->dispatchFolder, 0777, true);
    }

    /**
     * @return list<string>
     */
    public function listFolders(): array
    {
        return \array_values(
            \array_filter(
                \array_diff(\scandir($this->dispatchFolder) ?: [], ['.', '..']),
                fn (string $folder) => \is_dir($this->dispatchFolder . $folder)
            )
        );
    }
}
