<?php

namespace App\Services\System;

use App\Models\Category;
use App\Models\Product;
use App\Models\SystemConfiguration;
use App\Services\Manage\CuttingResultPriceResolver;
use App\Services\System\Setting\HomepageSettingService;
use App\Settings\SocialMediaSettings;
use App\Settings\SystemSettings;
use App\Support\Media\MediaPresenter;

class HomepageService
{
    public function __construct(
        private readonly CuttingResultPriceResolver $cuttingResultPriceResolver,
        private readonly HomepageSettingService $homepageSettingService,
    ) {}

    public function pageData(): array
    {
        $categories = Category::getActiveWithProducts();
        $products = $this->getProducts();

        $configuration = SystemConfiguration::instance();
        $logo = MediaPresenter::first($configuration, 'logo');
        $logoUrl = $logo['url'] ?? null;

        $settings = app(SystemSettings::class);
        $socialSettings = app(SocialMediaSettings::class);

        return [
            'categories' => $categories,
            'products' => $products,
            'appName' => $settings->app_name ?? 'DST Collection',
            'aboutApp' => $settings->about_app ?? '',
            'contactEmail' => $settings->email ?? '',
            'contactPhone' => $settings->phone ?? '',
            'contactAddress' => $settings->address ?? '',
            'logoUrl' => $logoUrl,
            'instagramUrl' => $socialSettings->instagram_url ?? null,
            'facebookUrl' => $socialSettings->facebook_url ?? null,
            'tiktokUrl' => $socialSettings->tiktok_url ?? null,
            'homepage' => $this->homepageSettingService->homepageData(),
        ];
    }

    private function getProducts()
    {
        $products = Product::getActiveWithVariantsAndCategories();

        $allVariantIds = $products
            ->flatMap(fn ($product) => $product->variants->pluck('id'))
            ->all();

        $allPricesByVariant = $this->cuttingResultPriceResolver->latestPricesForVariants($allVariantIds);

        return $products->map(function ($product) use ($allPricesByVariant) {
            $product->variants->each(function ($variant) use ($allPricesByVariant) {
                $variant->setAttribute('images', MediaPresenter::collection($variant, 'images'));
                $variantPrices = $allPricesByVariant->get($variant->id, collect());
                $variant->setAttribute(
                    'prices',
                    $variantPrices->map(fn ($price) => [
                        'type' => $price->price_type->value,
                        'type_label' => $price->price_type->label(),
                        'price' => (int) $price->price,
                        'price_formatted' => $price->price_formatted,
                    ])->values()->all(),
                );
            });

            return $product;
        });
    }
}
