<?php

namespace App\Models;

use App\Enums\ProjectStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Project extends Model
{
    use HasFactory, HasUlids;

    protected $fillable = ['name', 'domain', 'url'];

    protected function casts(): array
    {
        return ['status' => ProjectStatus::class, 'archived_at' => 'datetime'];
    }

    public function uniqueIds(): array { return ['ulid']; }
    public function getRouteKeyName(): string { return 'ulid'; }
    public function user(): BelongsTo { return $this->belongsTo(User::class); }
    public function owner(): BelongsTo { return $this->user(); }
    public function keywords(): HasMany { return $this->hasMany(Keyword::class); }
    public function competitors(): HasMany { return $this->hasMany(ProjectCompetitor::class); }
    public function scopeOwnedBy(Builder $query, User|int $owner): Builder
    {
        return $query->where('user_id', $owner instanceof User ? $owner->getKey() : $owner);
    }
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', ProjectStatus::Active)->whereNull('archived_at');
    }
    public function archive(): bool
    {
        return $this->forceFill(['status' => ProjectStatus::Archived, 'archived_at' => now()])->save();
    }
    public function restoreProject(): bool
    {
        return $this->forceFill(['status' => ProjectStatus::Active, 'archived_at' => null])->save();
    }
}
