<?php

namespace App\Services\Whatsapp;

use App\Models\WhatsappGroupLink;

class WhatsappInviteService
{
    public function __construct(
        private WhatsappContextService $context,
        private WhatsappInviteBundleService $bundleService,
        private WhatsappInviteNotificationService $notificationService
    ) {
    }

    public function send(array $payload): array
    {
        $mode = trim((string) ($payload['mode'] ?? ''));
        $schoolYear = trim((string) ($payload['school_year'] ?? '')) ?: $this->context->schoolYear();
        $semester = array_key_exists('semester', $payload)
            ? trim((string) ($payload['semester'] ?? ''))
            : $this->context->semester();

        $links = WhatsappGroupLink::getAllForTerm($schoolYear, $semester);
        $linkBySection = [];
        foreach ($links as $link) {
            $cid = (int) ($link->class_section_id ?? 0);
            if ($cid && !isset($linkBySection[$cid])) {
                $linkBySection[$cid] = $link->toArray();
            }
        }

        $bundles = [];
        if ($mode === 'parents') {
            $parentIds = array_map('intval', (array) ($payload['parent_ids'] ?? []));
            foreach ($parentIds as $pickedId) {
                if ($pickedId <= 0) {
                    continue;
                }
                $bundle = $this->bundleService->bundleForParent($pickedId, $linkBySection, $schoolYear, $semester);
                if ($bundle && !empty($bundle['emails']) && !empty($bundle['links'])) {
                    $bundles[] = $bundle;
                }
            }
        } elseif ($mode === 'class') {
            $classSectionId = (int) ($payload['class_section_id'] ?? 0);
            $classBundles = $this->bundleService->bundlesForClass($classSectionId, $linkBySection, $schoolYear, $semester);
            foreach ($classBundles as $bundle) {
                if (!empty($bundle['emails']) && !empty($bundle['links'])) {
                    $bundles[] = $bundle;
                }
            }
        } elseif ($mode === 'all') {
            $allBundles = $this->bundleService->bundlesForAll($linkBySection, $schoolYear, $semester);
            foreach ($allBundles as $bundle) {
                if (!empty($bundle['emails']) && !empty($bundle['links'])) {
                    $bundles[] = $bundle;
                }
            }
        }

        if (empty($bundles)) {
            return [
                'ok' => false,
                'message' => 'No recipients found (missing links or emails).',
                'triggered' => 0,
            ];
        }

        $consolidated = $this->bundleService->consolidateBundles($bundles);
        $result = $this->notificationService->dispatch($consolidated, $schoolYear, $semester);

        if (!($result['ok'] ?? false)) {
            return $result + ['ok' => false];
        }

        return [
            'ok' => true,
            'triggered' => (int) ($result['triggered'] ?? 0),
        ];
    }
}
