<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Mtc\MercuryDataModels\Finance\Santander\Models\SantanderProduct;

class SantanderProductController extends Controller
{
    public function index(): JsonResponse
    {
        $products = SantanderProduct::with([
                'attributeRates' => fn ($q) => $q->orderBy('rate'),
                'validations' => fn ($q) => $q->orderBy('period'),
                'capCodes',
            ])
            ->orderBy('product_id')
            ->get()
            ->map(fn (SantanderProduct $product) => [
                'product_id' => $product->product_id,
                'product_type_id' => $product->product_type_id,
                'finance_type' => $product->finance_type,
                'attribute_rate_desc' => $product->attribute_rate_desc,
                'default_rate' => $product->default_rate,
                'attribute_rates' => $product->attributeRates->map(fn ($rate) => [
                    'rate' => $rate->rate,
                    'min_balance' => $rate->min_balance,
                    'max_balance' => $rate->max_balance,
                    'min_period' => $rate->min_period,
                    'max_period' => $rate->max_period,
                    'min_vehicle_age' => $rate->min_vehicle_age,
                    'max_vehicle_age' => $rate->max_vehicle_age,
                ]),
                'validations' => $product->validations->map(fn ($v) => [
                    'period' => $v->period,
                    'min_deposit' => $v->min_deposit,
                    'max_deposit' => $v->max_deposit,
                    'min_rate' => $v->min_rate,
                    'rate' => $v->rate,
                    'min_amount_financed' => $v->min_amount_financed,
                    'max_amount_financed' => $v->max_amount_financed,
                    'min_vehicle_age_at_start' => $v->min_vehicle_age_at_start,
                    'max_vehicle_age_at_start' => $v->max_vehicle_age_at_start,
                    'max_vehicle_age_at_end' => $v->max_vehicle_age_at_end,
                ]),
                'capcode_count' => $product->capCodes->count(),
            ]);

        return response()->json($products);
    }
}
