<?php

namespace App\Models;

use App\Libs\Database\Eloquent\ContentTypeModel;
use App\Libs\Database\Eloquent\Traits\SafeSyncTrait;
use App\Models\GenericBackoffice\Traits\LanguageSupportTrait;
use App\Services\MicrosoftGraph\ModelChangeTrackingService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class WorkGroup extends ContentTypeModel
{
    use LanguageSupportTrait;
    use SafeSyncTrait;

    protected $hidden = ['languages', "websites"];
    protected $with = ['languages', "websites"];

    protected $fillable = [
        'title',
        'description',
        'status',
        'committee_id',
        'ms_id',
        'archive_active',
    ];

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_work_group')->withPivot('type');
    }

    public function committee() {
        return $this->belongsTo(Committee::class);
    }

    public function documentLists() {
        return $this->belongsToMany(DocumentList::class)->withPivot('position');
    }

    public function documentListsArchive() {
        return $this->belongsToMany(DocumentList::class, 'document_list_work_group_archive')->withPivot('position');
    }

    /**
     * Relationship polymorphic with ContactFolder
     */
    public function contactFolders()
    {
        return $this->morphMany(ContactFolder::class, 'folderable');
    }

    /**
     * The "booting" method of the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('visibleByBackendUser', function (Builder $builder) {
            $backendUser = auth()->guard('admin')->user();

            if ($backendUser && $backendUser->userType->id != 1) {
                $allowedCommitteeIds = DB::table('backend_user_committee')
                    ->where('backend_user_id', $backendUser->id)
                    ->pluck('committee_id')
                    ->toArray();

                if (!empty($allowedCommitteeIds)) {
                    $builder->whereIn('work_groups.committee_id', $allowedCommitteeIds);
                } else {
                    $builder->whereRaw('1 = 0');
                }
            }
            // If no backend user is authenticated (e.g., frontend user or artisan commands), don't apply filter
        });

        static::created(function ($workGroup) {
            $trackingService = app(ModelChangeTrackingService::class);
            $trackingService->trackWorkGroupCreated($workGroup);
        });

        static::deleting(function ($workGroup) {
            $trackingService = app(ModelChangeTrackingService::class);
            $trackingService->trackWorkGroupDeleted($workGroup);
        });

        static::updating(function ($workGroup) {
            // Track status changes
            if ($workGroup->isDirty('status')) {
                $oldStatus = $workGroup->getOriginal('status');
                $newStatus = $workGroup->status;

                $trackingService = app(ModelChangeTrackingService::class);
                $trackingService->trackWorkGroupStatusChanged($workGroup, $oldStatus, $newStatus);
            }
        });
    }
}
