<?php

namespace Myvetshop\Module\Clinique\Import\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;
    }

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

    /**
     * @param array<string, string|int|float|null> $line
     */
    public function dispatchLine(string $section, array $line): void
    {
        switch ($section) {
            case 'STORES':
                $fileName = ($line['id_veto_alcyon'] ?? $line['code_privilege']) . '.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 'CART_RULES':
                $id = $line['id_cart_rule'];
                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));
        }

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

        // Empêche la création de dossier pour les clients qui ne seront pas importés
        if (!\is_dir($customerFolder) && $section !== 'CUSTOMERS') {
            return;
        }

        $outputDir = $customerFolder . $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));
        }
    }

    /**
     * @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)
            )
        );
    }

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