<?php

namespace App;

use App\Contracts\InteractsWithContentSync;
use Illuminate\Support\Arr;
use Mtc\MercuryDataModels\PropertyCategory;
use Mtc\MercuryDataModels\ValuationAdjustment;

class ValuationAdjustmentRepository implements InteractsWithContentSync
{
    public function importRecord(array $entry): bool
    {
        $valuationAdjustment = ValuationAdjustment::query()->create(Arr::except($entry, ['id', 'rules']));

        $rulesData = array_map(function ($rule) {
            return Arr::except($rule, ['id', 'adjustment_id']);
        }, $entry['rules']);

        foreach ($rulesData as $ruleData) {
            $valuationAdjustment->rules()->create($ruleData);
        }

        return $valuationAdjustment->exists;
    }

    public function canBeImported(array $entry): bool
    {
        return !ValuationAdjustment::query()
            ->where('is_increase', $entry['is_increase'])
            ->where('adjustment_amount', $entry['adjustment_amount'])
            ->where('adjustment_type', $entry['adjustment_type'])
            ->exists();
    }

    public function exportToRemote(array $selections): array
    {
        return  PropertyCategory::query()
            ->with([
                'properties' => function ($query) use ($selections) {
                    $query->whereIn('id', $selections);
                },
                'fields' => function ($query) use ($selections) {
                    $query->whereIn('property_id', $selections);
                },
                'fields.values'
            ])
            ->whereHas('properties', function ($query) use ($selections) {
                $query->whereIn('id', $selections);
            })
            ->get()
            ->toArray();
    }

    public function checkImportEntryValidity(array $dataEntry, array $allEntries): array
    {
        $valuationAdjustmentExists = ValuationAdjustment::query()
            ->where('is_increase', $dataEntry['is_increase'])
            ->where('adjustment_amount', $dataEntry['adjustment_amount'])
            ->where('adjustment_type', $dataEntry['adjustment_type'])
            ->exists();

        $errors = [];
        if ($valuationAdjustmentExists) {
            $errors[] = 'Valuation Adjustment Already Exists';
        }

        return [
            'data' => $dataEntry,
            'errors' => $errors,
        ];
    }
}
