<?php

declare(strict_types=1);

namespace App\Platform\Shopee\EntityParse;

use App\Constants\ProductStatus;
use App\Model\Company;
use App\Model\Store;
use App\Platform\AbstractProductParse;
use App\Platform\Shopee\Constants\ItemStatus;
use Carbon\Carbon;
use Hyperf\Collection\LazyCollection;
use InvalidArgumentException;

/**
 * Shopee 产品解析器
 *
 * @TODO 待实现：参照 Tmall\EntityParse\Product 实现 Shopee 产品数据解析
 *
 * Shopee 产品原始数据结构示例：
 * {
 *   "item_id": 123456789,
 *   "item_name": "商品名称",
 *   "item_sku": "SKU001",
 *   "item_status": "NORMAL",
 *   "price_info": { "current_price": 99.00, "currency": "SGD" },
 *   "stock_info": { "current_stock": 100 },
 *   "image": { "image_url_list": ["https://..."] },
 *   "model_list": [
 *     { "model_id": 111, "model_sku": "SKU001-A", "current_price": 99.00, "stock_info": { "current_stock": 50 } }
 *   ],
 *   "create_time": 1640000000,
 *   "update_time": 1640100000
 * }
 *
 * 状态映射：
 * - NORMAL -> ACTIVE
 * - BANNED -> BANNED
 * - UNLIST -> INACTIVE
 * - REVIEWING -> REVIEWING
 * - SELLER_DELETE -> SELLER_DELETE
 * - SHOPEE_DELETE -> PLATFORM_DELETE
 */
class Product extends AbstractProductParse
{
    /**
     * 公司作用域匹配
     *
     * @param array $metadata
     * @return Company
     * @throws InvalidArgumentException
     */
    public function companyScopeMatch(array $metadata): Company
    {
        if (!isset($metadata['company_id'])) {
            throw new InvalidArgumentException('company_id is required in metadata');
        }

        $company_id = $metadata['company_id'];
        $company = Company::find($company_id);

        if (!$company) {
            throw new InvalidArgumentException("Company with ID {$company_id} not found");
        }

        return $company;
    }

    /**
     * 店铺作用域匹配
     *
     * @param array $metadata
     * @return Store
     * @throws InvalidArgumentException
     */
    public function storeScopeMatch(array $metadata): Store
    {
        if (!isset($metadata['platform_store_id'])) {
            throw new InvalidArgumentException('platform_store_id is required in metadata');
        }

        $platform_store_id = $metadata['platform_store_id'];
        $shopee_platform_id = 25;

        $store = Store::where('platform_id', '=', $shopee_platform_id)
            ->where('platform_store_id', '=', $platform_store_id)
            ->first();

        if (!$store) {
            throw new InvalidArgumentException("Shopee store with platform_store_id {$platform_store_id} not found");
        }

        return $store;
    }

    /**
     * 实体数据映射
     *
     * @TODO 待实现：解析 Shopee 产品原始数据
     *
     * @param array $raw_data 原始数据数组
     * @return LazyCollection
     */
    public function entityMap(array $raw_data): LazyCollection
    {
        // 参考 Tmall\EntityParse\Product::entityMap() 实现
        return LazyCollection::make(function () use ($raw_data) {
            $records = isset($raw_data[0]) ? $raw_data : [$raw_data];

            foreach ($records as $record) {
                // 无规格时返回单条记录，有规格时每个 model 返回一条记录
                yield $this->mapSingleProduct($record);
            }
        });
    }

    /**
     * 映射单个产品记录
     *
     * @param array $record 商品主记录
     * @param array|null $model 规格记录
     * @return array
     */
    private function mapSingleProduct(array $record): array
    {
        $raw = \json_encode($record);

        $platform_item_id = (string) ($record['item_id'] ?? '');

        $platform_model_id = $record['has_model'] ? (string) ($record['model_info']['model_id'] ?? '') : null;

        $price = $this->determinePriceAndCurrency($record);
        $gtin_code =  $record['has_model'] ?  strval($record['model_info']['gtin_code']) : $record['gtin_code'];

        $stock = $this->determineStoreNum($record);

        return [
            'company_id' => $this->getCompany()->id,
            'platform_id' => $this->getPlatform()->id,
            'store_id' => $this->getStore()->id,
            'status_id' => $this->getProductStatusId($record['item_status'] ?? 'NORMAL'),
            'type_id' => 1,
            'warehouse_id' => null,
            'sub_warehouse_id' => null,
            'platform_item_id' => $platform_item_id,
            'platform_model_id' => $platform_model_id,
            'origin_sku_id' => $model['model_sku'] ?? $record['item_sku'] ?? null,
            'mapped_sku_id' => null,
            'barcode' => $gtin_code == '00' ? null : $gtin_code,
            'hscode' => null,
            'bundled' => null,
            'price' => $price['0'] ?? '0.00',
            'currency' => $price['1'] ?? 'USD',
            'num' => $stock,
            'url' => null,
            'picture' => $record['image']['image_url_list'][0] ?? null,
            'name' => $record['item_name'] ?? null,
            'raw' => $raw,
            'ext' => null,
            'hash' => \md5($raw),
            'created_date' => isset($record['create_time'])
                ? Carbon::createFromTimestamp($record['create_time'])
                : null,
            'updated_date' => isset($record['update_time'])
                ? Carbon::createFromTimestamp($record['update_time'])
                : null,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
    }

    private function determinePriceAndCurrency(array $record): array | null
    {
        if(!empty($record['current_price']) && !empty($record['currency'])){
            return [strval($record['current_price']), $record['currency']];
        }

        if($record['has_model']){

            $model = $record['model_info'];

            $price_info = !empty($model['price_info']) ? $model['price_info']['0'] : null;
            
            if($price_info){
                return  [$price_info['current_price'], $price_info['currency']];
            } 

            return null;
        }

        if(!empty($record['price_info'])){

            $price_info = !empty($record['price_info']) ? $record['price_info']['0'] : null;
            
            if($price_info){
                return  [$price_info['current_price'], $price_info['currency']];
            } 

        }


        return null;
    }


     private function determineStoreNum(array $record): int
     {
        $stock = $record['has_model'] ? $record['model_info']['stock_info_v2'] : $record['stock_info_v2'];

        return $stock['summary_info']['total_available_stock'] ?? 0;
     }


    /**
     * 获取唯一键字段
     *
     * @return array
     */
    public function getUniqueBy(): array
    {
        return ['store_id', 'platform_item_id', 'platform_model_id'];
    }

    /**
     * 获取可更新字段列表
     *
     * @return array
     */
    public function getUpdateFields(): array
    {
        return [
            'status_id',
            'type_id',
            'warehouse_id',
            'sub_warehouse_id',
            'origin_sku_id',
            'mapped_sku_id',
            'barcode',
            'hscode',
            'bundled',
            'price',
            'currency',
            'num',
            'url',
            'picture',
            'name',
            'raw',
            'ext',
            'hash',
            'updated_date',
            'updated_at',
        ];
    }

    /**
     * 获取产品状态 ID
     *
     * 将 Shopee 产品状态映射到本地 ProductStatus 枚举
     *
     * @param string $platform_status Shopee 平台状态
     * @return int
     */
    public function getProductStatusId(string $platform_status): int
    {
        $status_map = [
            ItemStatus::NORMAL->name => ProductStatus::ACTIVE->value,
            ItemStatus::BANNED->name => ProductStatus::BANNED->value,
            ItemStatus::UNLIST->name => ProductStatus::INACTIVE->value,
            ItemStatus::REVIEWING->name => ProductStatus::REVIEWING->value,
            ItemStatus::SELLER_DELETE->name => ProductStatus::SELLER_DELETE->value,
            ItemStatus::SHOPEE_DELETE->name => ProductStatus::PLATFORM_DELETE->value,
        ];

        return $status_map[$platform_status] ?? ProductStatus::INACTIVE->value;
    }
}
