<?php
namespace Bot\Commands\AdminCommands;

use Bot\Services\FreeGoodsService;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class AdminfreeCommand extends AdminCommand
{
    protected $name = 'adminfree';
    protected $description = 'Manage FREE goods catalogue';
    protected $usage = '/adminfree <list|add|edit|status|delete>';
    protected $version = '1.0.0';

    private FreeGoodsService $goods;

    public function __construct($telegram, $update = null)
    {
        parent::__construct($telegram, $update);
        $this->goods = new FreeGoodsService();
    }

    public function execute(): ServerResponse
    {
        $payload = trim($this->getMessage()->getText(true) ?? '');
        if ($payload === '') {
            return $this->replyUsage();
        }
        [$command, $rest] = array_pad(explode(' ', $payload, 2), 2, '');
        $command = strtolower($command);
        return match ($command) {
            'list'   => $this->handleList(),
            'add'    => $this->handleAdd($rest),
            'edit'   => $this->handleEdit($rest),
            'status' => $this->handleStatus($rest),
            'delete' => $this->handleDelete($rest),
            default  => $this->replyUsage(),
        };
    }

    private function replyUsage(): ServerResponse
    {
        $text = "FREE goods commands:\n"
            . " `/adminfree list`\n"
            . " `/adminfree add <title>|<description>|[button_label]|[button_url]|[sort]|[status]|[parse_mode]`\n"
            . " `/adminfree edit <id> <field> <value>` (fields: title, description, button_label, button_url, sort_order, parse_mode)\n"
            . " `/adminfree status <id> <active|inactive>`\n"
            . " `/adminfree delete <id>`\n\n"
            . "Parse modes: markdown, markdownv2, html, text. Use `none` for empty button fields.";
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => $text,
            'parse_mode' => 'Markdown',
        ]);
    }

    private function handleList(): ServerResponse
    {
        $items = $this->goods->listAll();
        if (!$items) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'No FREE goods configured yet.',
            ]);
        }
        $lines = [];
        foreach ($items as $item) {
            $lines[] = sprintf(
                '#%d [%s] %s (button: %s | sort: %d)',
                $item['id'],
                strtoupper($item['status']),
                $item['title'],
                $item['button_label'] ?: '-',
                $item['sort_order']
            );
        }
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => implode("\n", $lines),
        ]);
    }

    private function handleAdd(string $payload): ServerResponse
    {
        $parts = array_map('trim', explode('|', $payload));
        if (count($parts) < 2) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Usage: /adminfree add <title>|<description>|[button_label]|[button_url]|[sort]|[status]|[parse_mode]',
            ]);
        }
        $title = $parts[0];
        $description = $parts[1];
        $buttonLabel = $this->nullIfEmpty($parts[2] ?? null);
        $buttonUrl = $this->nullIfEmpty($parts[3] ?? null);
        $sort = isset($parts[4]) ? (int) $parts[4] : 0;
        $status = isset($parts[5]) ? strtolower($parts[5]) : 'inactive';
        $status = $status === 'active' ? 'active' : 'inactive';
        $parseMode = $this->normalizeParseMode($parts[6] ?? null);
        $id = $this->goods->create($title, $description, $buttonLabel, $buttonUrl, $parseMode, $status, $sort);
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => sprintf('FREE good #%d created (%s).', $id, strtoupper($status)),
        ]);
    }

    private function handleEdit(string $payload): ServerResponse
    {
        $payload = trim($payload);
        if ($payload === '') {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Usage: /adminfree edit <id> <field> <value>',
            ]);
        }
        [$id, $field, $value] = array_pad(explode(' ', $payload, 3), 3, '');
        $id = (int) $id;
        if ($id <= 0 || $field === '' || $value === '') {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Provide id, field, and value.',
            ]);
        }
        $field = strtolower($field);
        if ($field === 'button_label' || $field === 'button_url') {
            $value = $this->nullIfEmpty($value);
        } elseif ($field === 'parse_mode') {
            $value = $this->normalizeParseMode($value);
        }
        if (!$this->goods->updateField($id, $field, $value)) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Update failed. Allowed fields: title, description, button_label, button_url, sort_order, parse_mode.',
            ]);
        }
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => sprintf('FREE good #%d updated.', $id),
        ]);
    }

    private function handleStatus(string $payload): ServerResponse
    {
        [$id, $status] = array_pad(explode(' ', trim($payload)), 2, '');
        $id = (int) $id;
        $status = strtolower($status);
        if ($id <= 0 || !in_array($status, ['active', 'inactive'], true)) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Usage: /adminfree status <id> <active|inactive>',
            ]);
        }
        $this->goods->setStatus($id, $status);
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => sprintf('FREE good #%d is now %s.', $id, strtoupper($status)),
        ]);
    }

    private function handleDelete(string $payload): ServerResponse
    {
        $id = (int) trim($payload);
        if ($id <= 0) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Usage: /adminfree delete <id>',
            ]);
        }
        $this->goods->delete($id);
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => sprintf('FREE good #%d deleted.', $id),
        ]);
    }

    private function normalizeParseMode(?string $mode): ?string
    {
        if ($mode === null) {
            return null;
        }
        $normalized = strtolower(trim($mode));
        return match ($normalized) {
            '', 'text', 'none', '-' => null,
            'markdown' => 'Markdown',
            'markdownv2' => 'MarkdownV2',
            'html' => 'HTML',
            default => null,
        };
    }

    private function nullIfEmpty(?string $value): ?string
    {
        if ($value === null) {
            return null;
        }
        $trimmed = trim($value);
        if ($trimmed === '' || strtolower($trimmed) === 'none') {
            return null;
        }
        return $trimmed;
    }
}
