<?php

namespace App\Models;

use App\Models\User;
use App\Models\Sprint;
use App\Models\Requirement;
use App\Models\UserOperation;
use Illuminate\Database\Eloquent\Model;
use App\Models\NonFunctionalRequirement;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Project extends Model
{
    /** @use HasFactory<\Database\Factories\ProjectFactory> */
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'status',
    ];

    public function requirements()
    {
        return $this->hasMany(Requirement::class);
    }

    public function nonFunctionalRequirements()
    {
        return $this->hasMany(NonFunctionalRequirement::class);
    }

    /**
     * The users that belong to the project.
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'user_operations', 'project_id', 'user_id')
            ->withPivot([
                'designation',
                'tech_skills',
                'experience',
                'interpersonal_relationship',
                'power',
                'influence',
            ])
            ->withTimestamps();
    }

    /**
     * Get the user operations pivot records.
     */
    public function userOperations()
    {
        return $this->hasMany(UserOperation::class);
    }

    public function sprintsThroughBacklogs()
    {
        if (!$this->id) {
            return Sprint::whereNull('id');
        }

        return Sprint::join('sprint_backlogs', 'sprints.id', '=', 'sprint_backlogs.sprint_id')
            ->join('requirements', 'sprint_backlogs.r_id', '=', 'requirements.id')
            ->where('requirements.project_id', $this->id)
            ->select('sprints.*')
            ->distinct();
    }

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