<?php

namespace App\Reporting\Repositories;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Enquiry;
use Mtc\MercuryDataModels\Vehicle;

class VehicleReportRepository
{
    public function performanceReport(array $filters = [])
    {
        $period = match ($filters['timeframe'] ?? 'all') {
            '1d' => 1,
            '7d' => 7,
            '30d' => 30,
            default => null
        };
        $query = Vehicle::query()
            ->with([
                'make',
                'model',
            ])
            ->withImageCount()
            ->withEnquiryCount($period)
            ->withReservationCount($period)
            ->withViewCount($period);
        foreach ($filters as $filter => $value) {
            $this->applyConditionToQuery($query, $filter, $value);
        }

        return $query->get()
            ->map(fn(Vehicle $vehicle) => [
                'id' => $vehicle->id,
                'VRM' => $vehicle->vrm_condensed,
                'Make' => $vehicle->make?->name,
                'Model' => $vehicle->model?->name,
                'Title' => $vehicle->title,
                'Price' => $vehicle->price,
                'Image Count' => $vehicle->image_count,
                'Days In Stock' => $vehicle->days_in_stock,
                'View Count' => $vehicle->view_count ?? 0,
                'Enquiries' => $vehicle->enquiry_count,
                'Reservations' => $vehicle->reservation_count,
            ]);
    }

    private function applyConditionToQuery(Builder $query, int|string $filter, mixed $value)
    {
        switch ($filter) {
            case 'status':
                match ($value) {
                    'published' => $query->where('is_published', 1),
                    'unpublished' => $query->where('is_published', 0),
                    default => $query,
                };
                break;
            case 'type':
                if ($value !== 'all') {
                    $query->where('type', $value);
                }
                break;
            case 'condition':
                match ($value) {
                    'used' => $query->used(),
                    'new' => $query->where('is_new', 1),
                    'ex-demo' => $query->where('is_demo', 1),
                    default => $query,
                };
                break;
        }
    }
}
