<?php

namespace App\Models;

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

class Requirement extends Model
{
    /** @use HasFactory<\Database\Factories\RequirementFactory> */
    use HasFactory;

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

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

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

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

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

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

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

    public function nonFunctionalRequirements()
    {
        return $this->belongsToMany(
            NonFunctionalRequirement::class,
            'sprint_backlogs',  // or a new pivot table if you want a cleaner one
            'r_id',             // foreign key on sprint_backlogs pointing to requirement
            'nfu_id'            // foreign key on sprint_backlogs pointing to NFR
        )->withTimestamps();
    }

}
