<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\PerformanceRun;

class Performance extends Model
{
    protected $guarded = [];

    public function troupe()
    {
        return $this->belongsTo(Troupe::class);
    }

    public function performanceType()
    {
        return $this->belongsTo(PerformanceType::class);
    }

    public function works()
    {
        return $this->belongsToMany(Work::class, 'performance_works')
            ->withPivot('act_order', 'notes')
            ->withTimestamps();
    }

    public function performanceWorks()
    {
        return $this->hasMany(PerformanceWork::class);
    }

    public function people()
    {
        return $this->belongsToMany(Person::class, 'performance_people')
            ->withPivot('performance_work_id', 'category', 'role_name', 'is_lead', 'credit_order', 'notes')
            ->withTimestamps();
    }

    public function performancePeople()
    {
        return $this->hasMany(PerformancePerson::class);
    }

    public function sources()
    {
        return $this->morphMany(Source::class, 'sourceable');
    }

    public function runs()
    {
        return $this->hasMany(PerformanceRun::class);
    }

    public function getDisplayNameAttribute(): string
    {
        $troupe = $this->troupe?->name ?? '組未設定';
        $type = $this->performanceType?->name ?? '公演区分未設定';

        $year = $this->runs()
            ->orderBy('start_date')
            ->value('start_date');

        $year = $year ? \Carbon\Carbon::parse($year)->year . '年 ' : '';

        $works = $this->performanceWorks()
            ->with('work')
            ->orderBy('act_order')
            ->get()
            ->pluck('work.title')
            ->filter()
            ->implode('』『');

        if ($works !== '') {
            $works = "『{$works}』";
        }

        return trim("{$year}{$troupe} {$type}{$works}");
    }
}
