<?php

namespace App\Models\Equipment;

use App\Entities\Equipment\CodeEntity;

class CodeModel extends EquipmentModel
{
    const TABLE = "codeinfo";
    const PK = "code";
    const TITLE = "code";
    protected $table            = self::TABLE;
    protected $primaryKey       = self::PK;
    protected $useAutoIncrement = false;
    protected $returnType       = CodeEntity::class;
    protected $allowedFields = [
        "code",
        "status",
        "updated_at"
    ];
    public function __construct()
    {
        parent::__construct();
    }
    public function getFormFieldRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            case $this->getPKField():
                // 수동입력인 경우
                if (!$this->useAutoIncrement) {
                    $rule = "required|regex_match[/^[0-9a-zA-Z]/]";
                    $rule .= in_array($action, ["create", "create_form"]) ? "|is_unique[{$this->table}.{$field}]" : "";
                } else {
                    $rule = "required|numeric";
                }
                break;
            case "status":
                $rule  = "required|trim|string";
                break;
            default:
                $rule = parent::getFormFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    protected function convertEntityData(string $action, string $field, array $formDatas, mixed $entity): mixed
    {
        switch ($field) {
            case $this->getPKField():
                $entity->$field = $formDatas[$field];
                break;
            default:
                $entity = parent::convertEntityData($action, $field, $formDatas, $entity);
                break;
        }
        return $entity;
    }
}
