<?php

namespace App\Models;

use App\Entities\ProductEntity;

class ProductModel extends BaseModel
{
    const STATUS_OUTOFSTOCK = "outofstock";
    const STATUS_SOLDOUT = "soldout";
    protected $table = "tw_product";
    protected $useAutoIncrement = false;
    protected $returnType = ProductEntity::class;
    protected $useSoftDeletes   = true;
    public function __construct()
    {
        parent::__construct('Product');
        $this->allowedFields = [
            ...$this->allowedFields,
            "category", "user_uid",
            'type', 'name', "photo", "cost", "price", "sale",
            "stock", "view_cnt",  "content", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return 'name';
    }

    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "category":
                $rules[$field] =  "required|string";
                break;
            case "user_uid":
                $rules[$field] = $this->getUUIDFieldRule('required');
                break;
            case $this->getTitleField():
                $rules[$field] =  "required|trim|string";
                break;
            case 'type':
                $rules[$field] =  "required|string";
                break;
            case 'photo':
                $rules[$field] = !$action ? "if_exist|string" : "is_image[{$field}]|mime_in[{$field},image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[{$field},300]|max_dims[{$field},2048,768]";
                break;
            case 'cost':
            case 'price':
            case 'stock':
                $rules[$field] =  "required|numeric";
                break;
            case 'sale':
                $rules[$field] =  "if_exist|numeric";
                break;
            case "content":
                $rules[$field] =  "required|string";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }

    public function getEntity($conditions): ProductEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 해당 데이터가 없습니다.");
    }
    public function create(array $formDatas): ProductEntity
    {
        return $this->create_process(new ProductEntity(), $formDatas);
    }
    public function modify(ProductEntity $entity, array $formDatas): ProductEntity
    {
        return $this->modify_process($entity, $formDatas);
    }

    //Index관련
    public function setIndexWordFilter(string $word): void
    {
        if ($word !== DEFAULTS['EMPTY']) {
            parent::setIndexWordFilter($word);
            $this->orLike("content", $word, "both");
        }
    }

    //조회수 올리기
    final public function addViewCount(ProductEntity $entity, int $view_cnt = 1): ProductEntity
    {
        $entity->view_cnt += $view_cnt;
        return $this->save_process($entity);
    }

    //장바구니에 넣기(재고수량빼기)
    final public function addCart(ProductEntity $entity, int $quantity): ProductEntity
    {
        $formDatas = array();
        if ($entity->stock == $quantity) {
            $formDatas['status'] = self::STATUS_OUTOFSTOCK;
        }
        $formDatas['stock'] = $entity->stock - $quantity;
        return $this->modify($entity, $formDatas);
    }
    //장바구니에 빼기(재고수량더하기)
    public function cancelCart(ProductEntity $entity, int $quantity)
    {
        $formDatas = array();
        if ($entity->status == self::STATUS_OUTOFSTOCK) {
            $formDatas['status'] = DEFAULTS['STATUS'];
        }
        $formDatas['stock'] = $entity->stock + $quantity;
        return $this->modify($entity, $formDatas);
    }
}
