<?php

namespace App\Models;

use App\Enums\StatusEnum;
use App\Models\Core\File;
use App\Traits\Filterable;
use App\Traits\ModelAction;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SocialPost extends Model
{
    use Filterable, ModelAction;
    protected $guarded = [];

    protected $casts = [
        'schedule_time' => 'datetime',
        'posted_at' => 'datetime',
        'repeat_schedule_end_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];


    public function files()
    {
        return $this->belongsToMany(File::class, 'social_post_files')
            ->withPivot(['caption', 'alt', 'order'])
            ->withTimestamps();
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, "user_id");
    }

    public function account(): BelongsTo
    {
        return $this->belongsTo(SocialAccount::class, "account_id");
    }

    public function platform(): BelongsTo
    {
        return $this->belongsTo(Platform::class, "platform_id");
    }

    public function scopeFilterByTab($query, ?string $tab = null)
    {
        $tab = $tab ?? request()->input('tab_key');


        return $query->when($tab && $tab !== 'all', function ($q) use ($tab) {
            switch ($tab) {
                case 'upcoming':
                    $q->where('schedule_time', '>', now());
                    break;
                case 'past':
                    $q->where('schedule_time', '<', now());
                    break;
                case 'drafts':
                    $q->where('is_draft', StatusEnum::true->status());
                    break;
            }
        });
    }

    public function metrics()
    {
        return $this->hasOne(PostMetric::class, 'post_id');
    }



    public function scopeFilterByPlatform(Builder $query)
    {
        $platformSlug = request()->input('slug');

        if ($platformSlug) {
            $query->whereHas('platform', function ($q) use ($platformSlug) {
                $q->where('slug', $platformSlug);
            });
        }

        return $query;
    }

    public function scopeFilterByContext($query)
    {
        $platformSlug = request('slug');
        $campaignId = request('campaign_id');
        $postId = request('post_id');

        return $query
            ->when($postId, fn($q) => $q->where('id', $postId))
            ->when(
                $campaignId,
                fn($q) =>
                $q->where('campaign_id', $campaignId)
            )
            ->when(
                !$campaignId && request()->routeIs('user.campaign.index'),
                fn($q) =>
                $q->whereNotNull('campaign_id')
            )
            ->when(
                $platformSlug,
                fn($q) =>
                $q->whereHas('platform', fn($q2) => $q2->where('slug', $platformSlug))
            );
    }






}
