<?php

namespace Database\Seeders\Concerns;

use Illuminate\Support\Facades\DB;

trait SeedsFromAlmacenSql
{
    /**
     * Seed destination tables by extracting INSERT statements from Almacen.sql.
     *
     * @param array<int|string, string> $tableMap
     */
    protected function seedTablesFromAlmacenSql(array $tableMap): void
    {
        $sqlPath = base_path('Almacen.sql');

        if (! is_file($sqlPath)) {
            return;
        }

        $sql = (string) file_get_contents($sqlPath);

        foreach ($tableMap as $destinationTable => $sourceTable) {
            if (is_int($destinationTable)) {
                $destinationTable = $sourceTable;
            }

            $pattern = sprintf(
                '/INSERT INTO\\s+`%s`\\s*\\((.*?)\\)\\s*VALUES\\s*(.*?);/is',
                preg_quote($sourceTable, '/')
            );

            if (! preg_match_all($pattern, $sql, $matches, PREG_SET_ORDER)) {
                continue;
            }

            foreach ($matches as $match) {
                $values = str_replace("'0000-00-00 00:00:00'", 'NULL', $match[2]);

                DB::unprepared(sprintf(
                    'INSERT INTO `%s` (%s) VALUES %s;',
                    $destinationTable,
                    $match[1],
                    $values
                ));
            }
        }
    }
}
