<?php

namespace App;

use Mtc\MercuryDataModels\TenantType;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleStockSyncLog;

class VehicleStockSyncLogRepository
{
    public function enabled(): bool
    {
        return tenant()->type === TenantType::DEFAULT->value;
    }

    public function store(Vehicle $vehicle, array $data, $provider, $action): void
    {
        VehicleStockSyncLog::query()
            ->create([
                'vehicle_id' => $vehicle->id,
                'provider' => $provider,
                'action' => $action,
                'data' => $data,
                'processed' => true,
                'synced_at' => now(),
            ]);
    }

    public function getImportRecords(Vehicle $vehicle)
    {
        return $vehicle->stockSyncLogs()
            ->imports()
            ->orderBy('synced_at', 'desc')
            ->paginate(4);
    }

    public function deleteAllExceptLast(Vehicle $vehicle): void
    {
        $lastImportRecord = $vehicle->stockSyncLogs()
            ->exports()
            ->last()
            ->first();

        $lastExportRecord = $vehicle->stockSyncLogs()
            ->exports()
            ->last()
            ->first();

        $preserveIds = collect([$lastImportRecord, $lastExportRecord])
            ->filter()
            ->pluck('id')
            ->all();

        $vehicle->stockSyncLogs()
            ->whereNotIn('id', $preserveIds)
            ->delete();
    }

    public function deleteOldLogs(): void
    {
        VehicleStockSyncLog::query()
            ->old()
            ->delete();

        VehicleStockSyncLog::query()
            ->select('vehicle_id')
            ->groupBy('vehicle_id')
            ->havingRaw('COUNT(*) > ' . VehicleStockSyncLog::RECORDS_TO_KEEP)
            ->pluck('vehicle_id')
            ->each(function ($vehicleId) {
                $keepIds = VehicleStockSyncLog::query()
                    ->where('vehicle_id', $vehicleId)
                    ->orderByDesc('synced_at')
                    ->limit(VehicleStockSyncLog::RECORDS_TO_KEEP)
                    ->pluck('id');

                VehicleStockSyncLog::query()
                    ->where('vehicle_id', $vehicleId)
                    ->whereNotIn('id', $keepIds)
                    ->delete();
            });
    }
}
