<?php

namespace App\Modules\HR\Recruitment\Models;

use App\Models\User;
use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Modules\HR\Departments\Models\Department;
use App\Modules\HR\Positions\Models\Position;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\SoftDeletes;

class RecruitmentVacancy extends Model
{
    use BelongsToTenant;
    use SoftDeletes;

    protected $table = 'recruitment_vacancies';

    protected $fillable = [
        'tenant_id',
        'reference_code',
        'job_request_id',
        'department_id',
        'position_id',
        'title',
        'slug',
        'description',
        'seo_title',
        'seo_description',
        'seo_keywords',
        'openings',
        'filled_positions',
        'status',
        'show_on_portal',
        'is_featured',
        'published_at',
        'closes_at',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'openings' => 'integer',
            'filled_positions' => 'integer',
            'show_on_portal' => 'boolean',
            'is_featured' => 'boolean',
            'published_at' => 'datetime',
            'closes_at' => 'date',
        ];
    }

    public function jobRequest(): BelongsTo
    {
        return $this->belongsTo(RecruitmentJobRequest::class, 'job_request_id');
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function position(): BelongsTo
    {
        return $this->belongsTo(Position::class);
    }

    public function applications(): HasMany
    {
        return $this->hasMany(RecruitmentApplication::class, 'vacancy_id');
    }

    public function interviews(): HasManyThrough
    {
        return $this->hasManyThrough(
            RecruitmentInterview::class,
            RecruitmentApplication::class,
            'vacancy_id',
            'application_id',
            'id',
            'id',
        );
    }

    public function offerLetters(): HasMany
    {
        return $this->hasMany(RecruitmentOfferLetter::class, 'vacancy_id');
    }

    public function hirings(): HasMany
    {
        return $this->hasMany(RecruitmentHiring::class, 'vacancy_id');
    }

    public function createdByUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}
