<?php

namespace App\Filament\Resources\ReturnResource\Pages;

use App\Filament\Resources\ReturnResource;
use App\Models\Lookups\ReturnReason;
use App\Models\Returns\ReturnDoc;
use App\Services\ReturnService;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;
use RuntimeException;

/**
 * Ported from ReturnController::store(). Everything is routed through
 * ReturnService::create() — the source controller never touches ReturnDoc
 * directly — including the reason-id→reason-code translation it does first.
 */
class CreateReturn extends CreateRecord
{
    protected static string $resource = ReturnResource::class;

    protected function handleRecordCreation(array $data): ReturnDoc
    {
        ReturnResource::assertBranchAccessible((int) $data['branch_id']);

        $items = $data['items'];

        // The service takes reason CODES, not ids — the controller resolves the
        // map up front, so the same lookup happens here.
        $reasonCodeMap = ReturnReason::whereIn(
            'id',
            collect($items)->pluck('return_reason_id')->unique(),
        )->pluck('code', 'id');

        try {
            return app(ReturnService::class)->create(
                header: [
                    'customer_id' => isset($data['customer_id']) ? (int) $data['customer_id'] : null,
                    'branch_id' => (int) $data['branch_id'],
                    'refund_method' => $data['refund_method'],
                    'note' => $data['note'] ?? null,
                ],
                lines: array_map(fn (array $item): array => [
                    'product_id' => (int) $item['product_id'],
                    'unit_id' => isset($item['unit_id']) ? (int) $item['unit_id'] : null,
                    'invoice_id' => (int) ($item['invoice_id'] ?? 0),
                    'invoice_item_id' => isset($item['invoice_item_id']) ? (int) $item['invoice_item_id'] : null,
                    'return_reason_code' => $reasonCodeMap[$item['return_reason_id']] ?? null,
                    'quantity' => (float) $item['quantity'],
                    'unit_price' => (float) $item['unit_price'],
                    'discount_type' => $item['discount_type'] ?? null,
                    'discount_value' => (float) ($item['discount_value'] ?? 0),
                    'is_add_back_to_stock' => (bool) ($item['is_add_back_to_stock'] ?? true),
                ], $items),
            );
        } catch (RuntimeException $e) {
            throw ValidationException::withMessages(['data.items' => $e->getMessage()]);
        }
    }

    protected function getRedirectUrl(): string
    {
        return ReturnResource::getUrl('index');
    }
}
