<?php

declare(strict_types=1);

namespace app\common\model;

use support\think\Model;
use think\model\relation\BelongsTo;

class Attachment extends Model
{
    protected string $table = 'attachment';
    protected string $pk = 'id';
    protected bool $autoWriteTimestamp = true;
    protected bool $updateTime = false;

    protected array $append = ['suffix', 'full_url'];

    public function getSuffixAttr($value, $row): string
    {
        if ($row['name'] ?? '') {
            $suffix = strtolower(pathinfo($row['name'], PATHINFO_EXTENSION));
            return $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        }
        return 'file';
    }

    public function getFullUrlAttr($value, $row): string
    {
        return full_url($row['url'] ?? '');
    }

    public function admin(): BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}
