<?php

namespace App\Services\AutoGrab;

/**
 * Shapes a raw AutoGrab feed row (the 37-column Parquet schema) into the "lead" array
 * that AutoGrabToVehicleImport expects.
 *
 * The feed already names its columns the same as the webhook lead fields, so this is
 * mostly about supplying safe defaults for the fields the webhook carried but the file
 * omits — most importantly tag_ids, whose absence would fatal AutoGrabToVehicleImport::add()
 * (in_array on a missing key). The file feed carries the cover and gallery image URLs but
 * still no transmission, coordinates, listing sources or listing descriptions; those columns
 * simply do not populate from it.
 */
class AutoGrabFeedRowMapper
{
    public function toLead(array $row): array
    {
        return array_merge($row, [
            // AutoGrab pre-filters junk (manually_excluded) and private sellers upstream, so
            // the file never contains them. Provide the keys add()/update() read directly so
            // they don't fatal or warn on the missing columns.
            'tag_ids' => $row['tag_ids'] ?? [],
            'seller_type' => $row['seller_type'] ?? null,
            'listing_sources' => $row['listing_sources'] ?? [],
        ]);
    }

    /**
     * The AutoGrab lead id (primary/dedup key for the whole feed).
     */
    public function id(array $row): ?string
    {
        $id = $row['id'] ?? null;

        return $id === null ? null : (string) $id;
    }

    /**
     * Last-change timestamp, used to keep the newest row when an id appears in more than
     * one shard of the same partition.
     */
    public function updatedAt(array $row): ?string
    {
        $value = $row['updated_at'] ?? null;

        return $value === null ? null : (string) $value;
    }
}
