<?php

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\DepartmentCorrelationPoint;
use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\RequestStack;

final class DepartmentCorrelationProvider implements ProviderInterface
{
    public function __construct(
        private readonly Connection $connection,
        private readonly RequestStack $requestStack
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable
    {
        $request = $this->requestStack->getCurrentRequest();
        $tax = $request?->query->get('tax', 'tfpb');
        $year = $request?->query->getInt('year', 2023);
        $department = (string) ($request?->query->get('department', ''));

        $rateColumn = $this->resolveRateColumn($tax);

        $sql = <<<SQL
            SELECT commune_code, $rateColumn AS rate, collected_volume
            FROM tax_data
            WHERE department_code = :department
              AND year = :year
              AND $rateColumn IS NOT NULL
              AND collected_volume IS NOT NULL
        SQL;

        $rows = $this->connection->fetchAllAssociative($sql, [
            'department' => $department,
            'year' => $year,
        ]);

        foreach ($rows as $row) {
            $item = new DepartmentCorrelationPoint();
            $item->communeCode = (string) $row['commune_code'];
            $item->rate = (float) $row['rate'];
            $item->collectedVolume = (float) $row['collected_volume'];
            yield $item;
        }
    }

    private function resolveRateColumn(?string $tax): string
    {
        return match (strtolower((string) $tax)) {
            'tfpnb' => 'rate_tfpnb',
            'tfpb' => 'rate_tfpb',
            'th' => 'rate_th',
            'cfe' => 'rate_cfe',
            default => 'rate_tfpb',
        };
    }
}
