<?php

namespace App\Models\Equipment;

use App\Entities\Equipment\ServerEntity;

class ServerModel extends EquipmentModel
{
    const TABLE = "serverinfo";
    const PK = "uid";
    const TITLE = "title";
    protected $table            = self::TABLE;
    // protected $useAutoIncrement = false;
    protected $primaryKey       = self::PK;
    protected $returnType       = ServerEntity::class;
    protected $allowedFields = [
        "clientinfo_uid",
        "serviceinfo_uid",
        "code",
        "type",
        "title",
        "price",
        "amount",
        "manufactur_at",
        "format_at",
        "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 "clientinfo_uid":
            case "serviceinfo_uid":
                $rule  = "permit_empty|numeric";
                break;
            case "price":
            case "amount":
                $rule  = "required|numeric";
                break;
            case "type":
            case "status":
                $rule = "required|trim|string";
                break;
            case "manufactur_at":
                $rule = "required|valid_date";
                break;
            case "format_at":
                $rule = "permit_empty|valid_date";
                break;
            default:
                $rule = parent::getFormFieldRule($action, $field);
                break;
        }
        return $rule;
    }

    //create용 장비코드 마지막번호 가져오기
    final public function getLastestCode(string $format, int $default): string
    {
        $entity = $this->selectMax($this->primaryKey)->first();
        $pk = (int) ($entity->getPK() ?? $default); // 정수로 강제 변환
        return sprintf($format, date('ymd'), $pk + 1);
    }
}
