<?php

namespace App\Http\Requests\Admin\Manage;

use App\Enums\OrderChannel;
use App\Enums\OrderStatus;
use App\Enums\PaymentType;
use App\Enums\Permission;
use App\Enums\PriceType;
use App\Enums\ProductStockQuality;
use App\Http\Requests\Concerns\ValidatesMediaUploads;
use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class OrderRequest extends FormRequest
{
    use ValidatesMediaUploads;

    public function authorize(): bool
    {
        $permission = $this->isMethod('POST')
            ? Permission::ORDERS_CREATE
            : Permission::ORDERS_UPDATE;

        return $this->user()?->can($permission->value) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $rules = [
            'customer_id' => ['nullable', 'integer', Rule::exists('customers', 'id')->whereNull('deleted_at')],
            'marketing_id' => ['nullable', 'integer', Rule::exists('users', 'id')->whereNull('deleted_at')],
            'channel' => ['required', Rule::enum(OrderChannel::class)],
            'price_type' => ['required', Rule::enum(PriceType::class)],
            'payment_type' => ['required', Rule::enum(PaymentType::class)],
            'is_affiliate' => ['nullable', 'boolean'],
            'tiktok_order_id' => [Rule::requiredIf(fn () => $this->channel === OrderChannel::TIKTOK->value), 'string', 'max:100'],
            'shopee_order_id' => [Rule::requiredIf(fn () => $this->channel === OrderChannel::SHOPEE->value), 'string', 'max:100'],
            'discount' => ['nullable', 'integer', 'min:0'],
            'nego_price' => ['nullable', 'integer', 'min:0'],
            'notes' => ['nullable', 'string'],
            'status' => ['nullable', Rule::enum(OrderStatus::class)],
            ...$this->photoRules(),
        ];

        if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
            $rules['items'] = ['required', 'array', 'min:1'];
            $rules['items.*.product_variant_id'] = [
                'required',
                'integer',
                Rule::exists('product_variants', 'id')->whereNull('deleted_at'),
            ];
            $rules['items.*.quantity'] = ['required', 'integer', 'min:1'];
            $rules['items.*.stock_quality'] = ['required', Rule::enum(ProductStockQuality::class)];
        }

        return $rules;
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'customer_id' => 'Pelanggan',
            'marketing_id' => 'Marketing',
            'channel' => 'Channel',
            'price_type' => 'Tipe Harga',
            'payment_type' => 'Tipe Pembayaran',
            'is_affiliate' => 'Pesanan Afiliasi',
            'tiktok_order_id' => 'ID Pesanan TikTok Shop',
            'shopee_order_id' => 'ID Pesanan Shopee',
            'discount' => 'Diskon',
            'nego_price' => 'Harga Nego',
            'notes' => 'Keterangan',
            'status' => 'Status Pesanan',
            'items' => 'Produk',
            'items.*.product_variant_id' => 'Varian Produk',
            'items.*.quantity' => 'Jumlah',
            'items.*.stock_quality' => 'Kualitas Stok',
            ...$this->photoUploadAttributes('Bukti Transaksi'),
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            // Skip customer validation for cashier role
            $isCashier = $this->user()?->hasRole('cashier') ?? false;

            if (! $isCashier && $this->filled('marketing_id') && $this->marketing_id !== 'none' && ! $this->filled('customer_id')) {
                $validator->errors()->add('customer_id', 'Pelanggan wajib diisi jika marketing dipilih.');
            }

            if ($this->filled('status') && $this->status === OrderStatus::COMPLETED->value) {
                if (! $this->user()?->can(Permission::ORDERS_COMPLETE->value)) {
                    $validator->errors()->add('status', 'Anda tidak memiliki izin untuk menandai pesanan sebagai selesai.');
                }
            }

            if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
                /** @var Order $order */
                $order = $this->route('order');

                if (! $order->status->isEditable()) {
                    $validator->errors()->add('status', 'Pesanan tidak dapat diubah.');
                }
            }

            $paymentType = $this->input('payment_type');
            if (in_array($paymentType, ['qris', 'transfer'], true)) {
                $hasExistingPhotos = false;

                if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
                    /** @var Order $order */
                    $order = $this->route('order');
                    $hasExistingPhotos = $order->hasMedia('photos');
                }

                $hasNewPhotos = $this->hasFile('photos');
                $isRemovingAll = ! empty($this->input('remove_media_ids')) && $hasExistingPhotos;

                if (! $hasExistingPhotos && ! $hasNewPhotos) {
                    $validator->errors()->add('photos', 'Bukti transaksi wajib diisi untuk pembayaran QRIS/Transfer.');
                } elseif ($isRemovingAll && ! $hasNewPhotos) {
                    $validator->errors()->add('photos', 'Bukti transaksi wajib diisi untuk pembayaran QRIS/Transfer.');
                }
            }
        });
    }
}
