<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdNetwork;
use App\Models\AdUnit;
use Illuminate\Http\Request;

class MonetizationController extends Controller
{
    /**
     * Get monetization configuration.
     * 
     * Returns active networks and ad units grouped by placement,
     * optimized for the mobile app's waterfall logic.
     */
    public function getConfig()
    {
        // Fetch active networks ordered by priority
        $networks = AdNetwork::where('is_active', true)
            ->orderByDesc('priority')
            ->get(['id', 'name', 'app_id', 'priority', 'config']);

        // Fetch active ad units for active networks
        $adUnits = AdUnit::where('ad_units.is_active', 1)
            ->whereHas('network', function ($query) {
                $query->where('is_active', true);
            })
            ->with(['network:id,name,priority'])
            ->orderBy('ad_network_id') // Consistent ordering: AdMob (id=1) before Facebook (id=2)
            ->get();

        // Group units by placement
        $placements = [];
        
        foreach ($adUnits as $unit) {
            $placement = $unit->placement_identifier;
            
            if (!isset($placements[$placement])) {
                $placements[$placement] = [
                    'frequency' => $unit->frequency, // Take frequency from the first unit found (usually AdMob if seeded first)
                    'grid_frequency' => $unit->grid_frequency,
                    'units' => []
                ];
            }

            // If this unit has a higher priority network or specific override (if we added unit priority),
            // we could sort here. For now, rely on Network Priority.
            
            $placements[$placement]['units'][] = [
                'network' => $unit->network->name,
                'unit_id' => $unit->ad_unit_id,
                'type' => $unit->type,
                'priority' => $unit->network->priority, // Network level priority
            ];
        }

        // Sort units within each placement by priority
        foreach ($placements as $key => $data) {
            usort($placements[$key]['units'], function ($a, $b) {
                return $b['priority'] <=> $a['priority'];
            });
        }

        return response()->json([
            'success' => true,
            'networks' => $networks,
            'placements' => $placements,
        ]);
    }
}
