<?php

namespace App\Models;

use App\Models\User;
use App\Models\Sprint;
use App\Models\Project;
use App\Models\Requirement;
use App\Models\SprintBacklog;
use App\Models\RequirementOperation;
use Illuminate\Database\Eloquent\Model;
use App\Models\NonFunctionalRequirementFinal;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class NonFunctionalRequirement extends Model
{
    /** @use HasFactory<\Database\Factories\NonFunctionalRequirementFactory> */
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'weight',
        'rank',
        'project_id',
    ];

    protected $table = 'non_functional_requirements';

    /**
     * Fixed set of NFR types with their descriptions.
     */
    public static function types(): array
    {
        return [
            ['name' => 'Reliability', 'description' => 'System reliability and uptime requirements'],
            ['name' => 'Performance', 'description' => 'System performance and response time requirements'],
            ['name' => 'Security', 'description' => 'Security and data protection requirements'],
            ['name' => 'Scalability', 'description' => 'System scalability and growth requirements'],
            ['name' => 'Usability', 'description' => 'User experience and usability requirements'],
        ];
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function sprints()
    {
        return $this->belongsToMany(Sprint::class, 'sprint_backlogs', 'nfu_id', 'sprint_id')
                    ->withPivot('status', 'r_id')
                    ->withTimestamps();
    }

    public function sprintBacklogs()
    {
        return $this->hasMany(SprintBacklog::class, 'nfu_id');
    }

    /**
     * Get the requirement operations for this non-functional requirement.
     */
    public function requirementOperations()
    {
        return $this->hasMany(RequirementOperation::class, 'nfu_id');
    }

    /**
     * Get the users associated with this non-functional requirement through operations.
     */
    public function usersThroughOperations()
    {
        return $this->belongsToMany(User::class, 'requirement_operations', 'nfu_id', 'user_id')
                    ->withPivot('nfu_value', 'status', 'r_id')
                    ->withTimestamps();
    }

    /**
     * Get the requirements associated with this non-functional requirement through operations.
     */
    public function requirementsThroughOperations()
    {
        return $this->belongsToMany(Requirement::class, 'requirement_operations', 'nfu_id', 'r_id')
                    ->withPivot('nfu_value', 'status', 'user_id')
                    ->withTimestamps();
    }
}
