<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\FileStore;

class CommissionService
{
    private FileStore $commissions;
    private CourseService $courses;
    private SettingsService $settings;

    public function __construct()
    {
        $this->commissions = new FileStore(storage_path('data/commissions.json'));
        $this->courses = new CourseService();
        $this->settings = new SettingsService();
    }

    public function createForPayment(array $payment): array
    {
        $existing = $this->findByPayment((int) $payment['id']);

        if ($existing) {
            return $existing;
        }

        $course = $this->courses->find((int) $payment['course_id']);
        $gross = (float) $payment['amount'];
        $percentage = (float) $this->settings->get('platform_commission_percentage', 20);
        $platformAmount = round($gross * ($percentage / 100), 2);
        $sellerAmount = round($gross - $platformAmount, 2);

        return $this->commissions->insert([
            'payment_id' => (int) $payment['id'],
            'order_id' => (int) $payment['order_id'],
            'course_id' => (int) $payment['course_id'],
            'course_title' => $course['title'] ?? $payment['course_title'] ?? 'Curso',
            'seller_type' => $course['owner_type'] ?? 'platform',
            'seller_id' => (int) ($course['owner_id'] ?? 0),
            'gross_amount' => $gross,
            'platform_percentage' => $percentage,
            'platform_amount' => $platformAmount,
            'seller_amount' => $sellerAmount,
            'currency' => 'MZN',
            'status' => 'available',
            'created_at' => date('c'),
            'updated_at' => date('c'),
        ]);
    }

    public function findByPayment(int $paymentId): ?array
    {
        foreach ($this->commissions->all() as $commission) {
            if ((int) ($commission['payment_id'] ?? 0) === $paymentId) {
                return $commission;
            }
        }

        return null;
    }

    public function all(array $filters = []): array
    {
        $items = $this->commissions->all();
        $sellerType = $filters['seller_type'] ?? '';
        $sellerId = (int) ($filters['seller_id'] ?? 0);

        if ($sellerType !== '') {
            $items = array_filter($items, fn (array $item): bool => ($item['seller_type'] ?? '') === $sellerType);
        }

        if ($sellerId > 0) {
            $items = array_filter($items, fn (array $item): bool => (int) ($item['seller_id'] ?? 0) === $sellerId);
        }

        usort($items, fn (array $a, array $b): int => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));

        return array_values($items);
    }

    public function totals(array $items): array
    {
        $gross = array_sum(array_map(fn (array $item): float => (float) $item['gross_amount'], $items));
        $platform = array_sum(array_map(fn (array $item): float => (float) $item['platform_amount'], $items));
        $seller = array_sum(array_map(fn (array $item): float => (float) $item['seller_amount'], $items));

        return [
            'gross' => $gross,
            'platform' => $platform,
            'seller' => $seller,
            'count' => count($items),
        ];
    }
}
