<?php

namespace App\Models\Supplier;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Leenooks\Traits\ScopeActive;

use App\Models\{Supplier,SupplierDetail};
use App\Traits\SiteID;

/**
 * Class Supplier\Type
 *
 * Attributes for supplier types:
 * + category				: This will return the category of the product (eg: domain, hosting, etc), based on the class, which is the basis for all other logic of these types.
 * + category_name			: A friendly name that can override category
 */

abstract class Type extends Model
{
	use SiteID,ScopeActive;

	protected const category_name = NULL;

	public function __get($key): mixed
	{
		return match ($key) {
			'category' => (new \ReflectionClass($this))->getShortName(),
			'category_lc' => strtolower($this->category),
			'category_name' => static::category_name ?: $this->category,

			'min_cost' => $this->setup_cost+$this->base_cost*$this->contract_term,
			'name' => $this->product_id ?: 'Supplier PID Unknown',
			'name_long' => $this->product_desc ?: 'Supplier NAME Unknown',

			'supplier' => $this->supplier_detail->supplier,

			default => parent::__get($key),
		};
	}

	/* RELATIONS */

	/**
	 * The offering supplied with this product
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	final public function products()
	{
		return $this->hasMany(static::ProductModel,'supplier_item_id','id');
	}

	final public function supplier_detail()
	{
		return $this->belongsTo(SupplierDetail::class);
	}

	/* ATTRIBUTES */

	final public function getContractTermAttribute(?int $val): int
	{
		return $val ?: 1;
	}

	public function getSetupCostAttribute(?float $val): float
	{
		return $val ?: 0;
	}

	public function validation(): array
	{
		return [
			'id' => [
				'nullable',
				'numeric',
				sprintf('exists:%s,id',static::getTable())
			],
			'offering_type' => ['required',Rule::in(Supplier::offeringTypeKeys()->toArray())],
			'supplier_detail_id' => 'required|exists:supplier_details,id',
			'active' => 'sometimes|accepted',
			'base_cost' => 'required|numeric|min:0',
			'setup_cost' => 'nullable|numeric|min:0',
			'contract_term' => 'nullable|numeric|min:1',
			'product_id' => 'required|string|min:2',
			'product_desc' => 'required|string|min:2',
		];
	}
}