<?php
namespace Jaga\Traits;

trait ThrowableModel
{
    /**
     * Find the model instance or throw exception if fail to find
     *
     * @return Oject model
     */
    public static function findOrFail($params, $trash = false)
    {
        $model = self::findFirst($params);
        $modelName = property_exists(get_called_class(), 'throwableModelName') ? static::$throwableModelName :  static::class;
        
        $def = ' (';
        if (is_array($params)) {
            $param = $params[0];
            if (array_key_exists('bind', $params)) {
                $binds = $params['bind'];

                foreach ($binds as $key => $bind) {
                    $param = str_replace($param, ':'.$key.':', $bind);
                }
            }
            $def .= $param;
        } else {
            $def .= $params;
        }

        $def .= ') ';

        if (empty($model)) {

            throw new \CustomErrorException(
                \BaseResponse::INVALID_REQUEST, 
                $modelName . $def . 'Tidak Ditemukan'
            );
        }

        // If model use softDelete traits
        if (
            method_exists($model, 'restore') && 
            property_exists($model, 'deleted_at') 
        ) {
            if (!$trash && !empty($model->deleted_at)) {
                throw new \CustomErrorException(
                    \BaseResponse::INVALID_REQUEST, 
                    $modelName . $def . 'Sudah Terhapus'
                );
            }
        }

        return $model;
    }
}