<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$limit = min(intval($_GET['limit'] ?? 20), 50);

// Get friend IDs
$friends = $db->get('friendships', [
    'or' => "(requester_id.eq.{$userId},addressee_id.eq.{$userId})",
    'status' => 'eq.accepted',
    'select' => 'requester_id,addressee_id'
]);

$friendIds = [$userId];
if (is_array($friends) && !isset($friends['error'])) {
    foreach ($friends as $f) {
        $friendIds[] = $f['requester_id'] === $userId ? $f['addressee_id'] : $f['requester_id'];
    }
}

$idList = implode(',', $friendIds);

// Get activity from friends + self
$sdb = supabaseService();
$activity = $sdb->get('activity_feed', [
    'actor_id' => "in.({$idList})",
    'select' => 'id,actor_id,action,target_type,target_id,metadata,created_at',
    'order' => 'created_at.desc',
    'limit' => $limit
]);

// Get actor profiles
$actorIds = array_unique(array_column($activity ?: [], 'actor_id'));
$profiles = [];
if (!empty($actorIds)) {
    $profileList = implode(',', $actorIds);
    $profileData = $sdb->get('profiles', [
        'id' => "in.({$profileList})",
        'select' => 'id,username,display_name,avatar_url'
    ]);
    if (is_array($profileData) && !isset($profileData['error'])) {
        foreach ($profileData as $p) {
            $profiles[$p['id']] = $p;
        }
    }
}

// Enrich activity with actor info
$result = [];
if (is_array($activity) && !isset($activity['error'])) {
    foreach ($activity as $a) {
        $a['actor'] = $profiles[$a['actor_id']] ?? ['username' => 'Player'];
        $result[] = $a;
    }
}

jsonResponse(['activity' => $result]);
