<?php

namespace App\Models;

use App\Enums\OrderChannel;
use App\Enums\OrderStatus;
use App\Enums\PaymentType;
use App\Enums\PriceType;
use App\Models\Concerns\HasModuleMedia;
use App\Models\Concerns\InteractsWithActivityLog;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Validation\ValidationException;
use Spatie\MediaLibrary\HasMedia;

#[Guarded(['id'])]
#[Appends([
    'channel_label',
    'creator_name',
    'discount_formatted',
    'marketing_name',
    'nego_price_formatted',
    'payment_type_label',
    'price_type_label',
    'status_label',
    'subtotal_formatted',
    'total_amount_formatted',
    'created_at_formatted',
])]
class Order extends Model implements HasMedia
{
    // 1. Use Trait
    use HasFactory, HasModuleMedia, InteractsWithActivityLog, SoftDeletes;

    // 2. Casting
    protected function casts(): array
    {
        return [
            'channel' => OrderChannel::class,
            'is_affiliate' => 'boolean',
            'marketplace_settings_snapshot' => 'array',
            'nego_price' => 'integer',
            'payment_type' => PaymentType::class,
            'price_type' => PriceType::class,
            'status' => OrderStatus::class,
            'subtotal' => 'integer',
            'total_amount' => 'integer',
        ];
    }

    // 3. Scope (grouped by column, then alphabetical)
    // Column Group: channel
    #[Scope]
    protected function shopee(Builder $query): void
    {
        $query->where('channel', OrderChannel::SHOPEE);
    }

    #[Scope]
    protected function store(Builder $query): void
    {
        $query->where('channel', OrderChannel::STORE);
    }

    #[Scope]
    protected function tiktok(Builder $query): void
    {
        $query->where('channel', OrderChannel::TIKTOK);
    }

    // Column Group: is_affiliate
    #[Scope]
    protected function affiliate(Builder $query): void
    {
        $query->where('is_affiliate', true);
    }

    #[Scope]
    protected function nonAffiliate(Builder $query): void
    {
        $query->where('is_affiliate', false);
    }

    // Column Group: payment_type
    #[Scope]
    protected function cash(Builder $query): void
    {
        $query->where('payment_type', PaymentType::CASH);
    }

    #[Scope]
    protected function marketplace(Builder $query): void
    {
        $query->where('payment_type', PaymentType::MARKETPLACE);
    }

    #[Scope]
    protected function qris(Builder $query): void
    {
        $query->where('payment_type', PaymentType::QRIS);
    }

    #[Scope]
    protected function transfer(Builder $query): void
    {
        $query->where('payment_type', PaymentType::TRANSFER);
    }

    // Column Group: price_type
    #[Scope]
    protected function agent(Builder $query): void
    {
        $query->where('price_type', PriceType::AGENT);
    }

    #[Scope]
    protected function distributor(Builder $query): void
    {
        $query->where('price_type', PriceType::DISTRIBUTOR);
    }

    #[Scope]
    protected function retail(Builder $query): void
    {
        $query->where('price_type', PriceType::RETAIL);
    }

    #[Scope]
    protected function grosir(Builder $query): void
    {
        $query->where('price_type', PriceType::GROSIR);
    }

    #[Scope]
    protected function hargaModal(Builder $query): void
    {
        $query->where('price_type', PriceType::HARGA_MODAL);
    }

    #[Scope]
    protected function shopeePrice(Builder $query): void
    {
        $query->where('price_type', PriceType::SHOPEE);
    }

    #[Scope]
    protected function subAgent(Builder $query): void
    {
        $query->where('price_type', PriceType::SUB_AGENT);
    }

    #[Scope]
    protected function tiktokPrice(Builder $query): void
    {
        $query->where('price_type', PriceType::TIKTOK);
    }

    // Column Group: status
    #[Scope]
    protected function cancelled(Builder $query): void
    {
        $query->where('status', OrderStatus::CANCELLED);
    }

    #[Scope]
    protected function completed(Builder $query): void
    {
        $query->where('status', OrderStatus::COMPLETED);
    }

    #[Scope]
    protected function pending(Builder $query): void
    {
        $query->where('status', OrderStatus::PENDING);
    }

    #[Scope]
    protected function processing(Builder $query): void
    {
        $query->where('status', OrderStatus::PROCESSING);
    }

    // 4. Attribute
    public function channelLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->channel->label(),
        );
    }

    public function createdAtFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->created_at?->translatedFormat('l, d F Y H:i'),
        );
    }

    public function creatorName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->createdBy?->profile?->full_name ?? $this->createdBy?->username ?? '-',
        );
    }

    public function discountFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->discount, 0, ',', '.'),
        );
    }

    public function marketingName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->marketing?->profile?->full_name ?? $this->marketing?->username ?? '-',
        );
    }

    public function negoPriceFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->nego_price !== null ? 'Rp '.number_format($this->nego_price, 0, ',', '.') : null,
        );
    }

    public function paymentTypeLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->payment_type->label(),
        );
    }

    public function priceTypeLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->price_type->label(),
        );
    }

    public function statusLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status->label(),
        );
    }

    public function subtotalFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->subtotal, 0, ',', '.'),
        );
    }

    public function totalAmountFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->total_amount, 0, ',', '.'),
        );
    }

    // 5. Other Methods
    public static function mediaModuleName(): string
    {
        return 'order';
    }

    public function ensureEditable(): void
    {
        if (! $this->status->isEditable()) {
            throw ValidationException::withMessages([
                'status' => 'Pesanan tidak dapat diubah.',
            ]);
        }
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('photos');
    }

    // 6. Relation
    public function cashTransaction(): BelongsTo
    {
        return $this->belongsTo(CashTransaction::class);
    }

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

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

    public function items(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

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