<?php

namespace App\Models;

use App\Enums\CooperationStatus;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Swindon\FilamentHashids\Traits\HasHashid;

class Cooperation extends Model implements HasMedia
{
    use HasFactory, HasHashid, InteractsWithMedia, SoftDeletes;

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'initial_submission_date' => 'date',
            'final_submission_date' => 'date',
            'payment_amount' => 'integer',
            'payment_date' => 'date',
            'completed_at' => 'date',
            'status' => CooperationStatus::class,
        ];
    }

    #[Scope]
    protected function pending(Builder $query): void
    {
        $query->where('status', CooperationStatus::PENDING);
    }

    #[Scope]
    protected function assignment(Builder $query): void
    {
        $query->where('status', CooperationStatus::ASSIGNMENT);
    }

    #[Scope]
    protected function verification(Builder $query): void
    {
        $query->where('status', CooperationStatus::VERIFICATION);
    }

    #[Scope]
    protected function payment(Builder $query): void
    {
        $query->where('status', CooperationStatus::PAYMENT);
    }

    #[Scope]
    protected function completed(Builder $query): void
    {
        $query->where('status', CooperationStatus::COMPLETED);
    }

    public function cooperationMedias(): HasMany
    {
        return $this->hasMany(CooperationMedia::class);
    }

    public function partnerMedia(): BelongsToMany
    {
        return $this->belongsToMany(PartnerMedia::class, 'cooperation_media')
            ->using(CooperationMedia::class)
            ->withPivot(['status'])
            ->withTimestamps();
    }

    public function payments(): HasManyThrough
    {
        return $this->hasManyThrough(
            CooperationPayment::class,
            CooperationMedia::class,
            'cooperation_id',
            'cooperation_media_id'
        );
    }

    public function proposals(): HasMany
    {
        return $this->hasMany(CooperationProposal::class);
    }

    public function reports(): HasManyThrough
    {
        return $this->hasManyThrough(
            Report::class,
            MediaTaskAssignment::class,
            'task_assignment_id',
            'media_task_assignment_id'
        );
    }

    public function taskAssignment(): HasOne
    {
        return $this->hasOne(TaskAssignment::class);
    }
}
