<?php

namespace App\Models;

use App\Models\Traits\Filterable;
use App\Models\Traits\SelectOptions;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class UnitType extends Model
{
  use HasFactory, Filterable, SelectOptions;

  protected $fillable = [
    'code',
    'name',
  ];

  protected static function booted(): void
  {
    static::creating(function (UnitType $unitType) {
      if (!empty($unitType->name)) {
        $unitType->name = Str::title(Str::lower($unitType->name));
      }
      if (empty($unitType->code) && !empty($unitType->name)) {
        $unitType->code = static::generateUniqueCode($unitType->name, 4);
      } else {
        $unitType->code = Str::lower((string) $unitType->code);
      }
    });
  }

  public static function generateUniqueCode(string $value, int $maxLen = 4): string
  {
    $maxLen = max(1, min(10, $maxLen));

    $raw = Str::slug($value, '');
    $raw = preg_replace('/[aiueo]/i', '', $raw);
    $raw = Str::lower($raw ?? '');

    if ($raw === '') {
      $raw = 'unit';
    }

    $base = Str::substr($raw, 0, $maxLen);

    if (!static::where('code', $base)->exists()) {
      return $base;
    }


    for ($i = 1; $i <= 9999; $i++) {
      $suffix = (string) $i;
      $prefixLen = $maxLen - strlen($suffix);

      if ($prefixLen <= 0) {
        break;
      }

      $candidate = Str::substr($base, 0, $prefixLen) . $suffix;

      if (!static::where('code', $candidate)->exists()) {
        return $candidate;
      }
    }


    return Str::lower(Str::random($maxLen));
  }

  public function budgetDetail()
  {
    return $this->hasMany(BudgetDetail::class, 'unit_type_id');
  }

  public function transaction()
  {
    return $this->hasMany(Transaction::class, 'unit_type_id');
  }

  public function userUnitType()
  {
    return $this->hasOne(UserUnitType::class);
  }
}
