<?php

namespace App\Actions\Shop;

use App\Models\PwShop;
use App\Models\PwShopLog;
use App\Models\User;
use App\Services\Api\ApiFactory;
use App\Services\ItemDataService;
use Illuminate\Support\Facades\Log;

final class PurchaseItemAction
{
    public function __construct(
        private ApiFactory $apiFactory,
        private ItemDataService $itemDataService,
    ) {}

    /**
     * @return array{success: bool, message: string}
     */
    public function handle(User $user, PwShop $item, int $characterId, int $quantity): array
    {
        $api = $this->apiFactory->make($user->ID);

        if (! $api->serverOnline()) {
            return ['success' => false, 'message' => 'Server is currently offline. Please try again later.'];
        }

        $itemData = $this->itemDataService->getItemData($item->item_id);
        $itemName = $itemData['name'] ?? "Item #{$item->item_id}";
        $totalPrice = $item->price * $quantity;

        if ($user->gold < $totalPrice) {
            return ['success' => false, 'message' => 'Insufficient gold. You need '.number_format($totalPrice).' gold.'];
        }

        $mailItem = [
            'id' => $item->item_id,
            'pos' => 0,
            'count' => $item->count * $quantity,
            'max_count' => $item->count * $quantity,
            'data' => $item->octet ?? '',
            'proctype' => $item->proctype ?? 16403,
            'expire_date' => 0,
            'guid1' => 0,
            'guid2' => 0,
            'mask' => $item->mask ?? 1,
        ];

        $title = 'Shop Purchase';
        $message = 'Thank you for your purchase: '.$itemName.' x'.($item->count * $quantity);

        try {
            $result = $api->sendMail($characterId, $title, $message, 0, $mailItem);

            if (! $result) {
                return ['success' => false, 'message' => 'Failed to send item. Please try again later.'];
            }

            $user->gold -= $totalPrice;
            $user->save();

            PwShopLog::create([
                'shop_item_id' => $item->id,
                'user_id' => $user->ID,
                'quantity' => $quantity,
                'total_price' => $totalPrice,
                'item_data' => [
                    'item_id' => $item->item_id,
                    'item_name' => $itemName,
                    'count' => $item->count,
                    'price' => $item->price,
                    'character_id' => $characterId,
                ],
            ]);

            return ['success' => true, 'message' => 'Purchase successful! Check your in-game mailbox.'];
        } catch (\Exception $e) {
            Log::error('Shop purchase failed', [
                'user_id' => $user->ID,
                'item_id' => $item->id,
                'error' => $e->getMessage(),
            ]);

            return ['success' => false, 'message' => 'An error occurred: '.$e->getMessage()];
        }
    }
}
