<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Resources\SalesChannelList;
use App\IntegrationRepository;
use App\ReportTypes\VehicleReport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\SalesChannelHistory;
use Mtc\MercuryDataModels\SalesChannelRule;

class SalesChannelController extends Controller
{
    public function index(IntegrationRepository $repository): SalesChannelList
    {
        return new SalesChannelList($repository->getEnabledForType('sales-channels'));
    }

    public function show(string $channel, IntegrationRepository $repository): array
    {
        $enabled = $repository->getEnabledForType('sales-channels');
        if (empty($enabled[$channel])) {
            abort(404);
        }

        return [
            'conditions' => $this->getConditionsForDisplay($channel),
            'data_options' => $this->getDataOptions(),
            'available_fields' => $this->getFieldTypes(),
            'name' => App::make($enabled[$channel]['class'])->name(),
            'channel' => $enabled[$channel],
            'logs' => SalesChannelHistory::query()
                ->where('channel', $channel)
                ->latest()
                ->take(50)
                ->get()
        ];
    }

    public function update(Request $request, string $channel)
    {
        SalesChannelRule::query()->updateOrCreate(
            [
                'channel' => $channel,
            ],
            [
                'conditions' => $this->getStorableConditions($request->input('conditions')),
            ]
        );
    }

    private function getStorableConditions(array $conditions): array
    {
        return collect($conditions)->map(function ($condition) {
            $condition['value'] = $condition['value']['operator'] == 'in'
                ? $this->convertConditionValueToArray($condition['value'])
                : $condition['value'];

            return $condition;
        })->toArray();
    }

    private function convertConditionValueToArray(array $value): array
    {
        $values = explode(',', $value['value']);
        $values = collect($values)->map(fn($value) => trim($value))->toArray();
        $value['value'] = $values;
        return $value;
    }

    private function getConditionsForDisplay(string $channel): array
    {
        $conditions = SalesChannelRule::query()->where('channel', '=', $channel)->first()?->conditions;

        return collect($conditions)->map(function ($condition) {

            if ($condition['value']['operator'] == 'in' && is_array($condition['value']['value'])) {
                $condition['value']['value'] = implode(',', $condition['value']['value']);
            }

            return $condition;
        })->toArray();
    }

    private function getDataOptions(): array
    {
        return [
            'operators' => collect(config('reports.operators', []))
                ->map(fn ($type) => [
                    'id' => $type,
                    'name' => __('reports.operators.' . $type),
                ])->values(),
        ];
    }

    private function getFieldTypes(): array
    {
        return collect(App::make(VehicleReport::class)->columns())
            ->map(fn ($name, $id) => [
                'id' => $id,
                'name' => $name,
            ])->values()->toArray();
    }
}
