<?php

namespace App\Models;

use App\Models\Backoffice\MediaItem;
use App\Models\Backoffice\Support\ContentTypeModel;
use App\Models\Backoffice\Traits\LanguageSupportTrait;

class Result extends ContentTypeModel
{
    use LanguageSupportTrait;

    protected $casts = [
        'result_date' => 'datetime',
        'updated_date' => 'datetime',
        'is_public' => 'bool',
    ];
    protected $hidden = ['languages', "websites"];
    protected $with = ['languages', "websites"];

    public function competition()
    {
        return $this->belongsTo(Competition::class);
    }

    public function image()
    {
        return $this->belongsTo(MediaItem::class);
    }

    public function images()
    {
        return $this->belongsToMany(MediaItem::class, 'result_images');
    }

    public function homepageImage()
    {
        return $this->belongsTo(MediaItem::class);
    }

    public function pdfDocument()
    {
        return $this->belongsTo(MediaItem::class);
    }

    public function winners()
    {
        return $this->hasMany(ResultWinner::class);
    }

    public function otherDates()
    {
        return $this->hasMany(ResultDate::class);
    }

    public function juryGroups()
    {
        return $this->hasMany(JuryGroup::class);
    }

    public function targetGroups()
    {
        return $this->belongsToMany(TargetGroup::class, 'result_target_group');
    }

    public function buildingTypes()
    {
        return $this->belongsToMany(BuildingType::class, 'result_building_types', 'result_id', 'building_type_id')
            ->withPivot('position')
            ->orderBy('result_building_types.position');
    }

    public function coordinationGroups()
    {
        return $this->hasMany(CoordinationGroup::class);
    }

    public function trackedResult()
    {
        return $this->hasOne(TrackedResult::class);
    }

    public function watchlists()
    {
        return $this->belongsToMany(Watchlist::class, 'watchlist_results', 'result_id', 'watchlist_id');
    }

    // Prevents loading all watchlists when accessing the relation if not eager loaded with user filter
    public function getWatchlistsAttribute()
    {
        return $this->relationLoaded('watchlists') ? $this->getRelationValue('watchlists') : collect();
    }
}
