<?php

declare(strict_types=1);

final class TaskBoxTypeService
{
    public static function ensureTable(PDO $pdo): void
    {
        $pdo->exec(
            "CREATE TABLE IF NOT EXISTS task_box_types (
                task_id INT NOT NULL PRIMARY KEY,
                glue_box_count INT NOT NULL DEFAULT 0,
                bait_box_count INT NOT NULL DEFAULT 0,
                efk_count INT NOT NULL DEFAULT 0,
                updated_by INT NULL,
                updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_task_box_types_updated_at (updated_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
        );
    }

    public static function getCounts(PDO $pdo, int $taskId): array
    {
        self::ensureTable($pdo);

        $stmt = $pdo->prepare('SELECT glue_box_count, bait_box_count, efk_count FROM task_box_types WHERE task_id = :id LIMIT 1');
        $stmt->execute(['id' => $taskId]);
        $row = $stmt->fetch();

        return [
            'glue_box_count' => (int)($row['glue_box_count'] ?? 0),
            'bait_box_count' => (int)($row['bait_box_count'] ?? 0),
            'efk_count' => (int)($row['efk_count'] ?? 0),
        ];
    }

    public static function setCounts(PDO $pdo, int $taskId, int $glueCount, int $baitCount, int $efkCount, ?int $byUserId = null): void
    {
        self::ensureTable($pdo);

        $glueCount = max(0, $glueCount);
        $baitCount = max(0, $baitCount);
        $efkCount = max(0, $efkCount);

        $stmt = $pdo->prepare(
            'INSERT INTO task_box_types (task_id, glue_box_count, bait_box_count, efk_count, updated_by)
             VALUES (:id, :g, :b, :e, :by)
             ON DUPLICATE KEY UPDATE
                glue_box_count = VALUES(glue_box_count),
                bait_box_count = VALUES(bait_box_count),
                efk_count = VALUES(efk_count),
                updated_by = VALUES(updated_by),
                updated_at = CURRENT_TIMESTAMP'
        );
        $stmt->execute([
            'id' => $taskId,
            'g' => $glueCount,
            'b' => $baitCount,
            'e' => $efkCount,
            'by' => $byUserId,
        ]);
    }
}
