<?php

namespace Modules\Inventory\DTO;

use Illuminate\Http\Request;
use Modules\Accounts\Enums\TransactionTypeEnum;
use Modules\Accounts\Models\AccountVoucherLine;

class VoucherLineData
{
    private function __construct(
        public int $accountId,
        public string $type,
        public float $debit = 0.0,
        public float $credit = 0.0,
        public ?string $description = null,
    ) {}

    public static function fromDebit(int $accountId, float $amount, ?string $description = null): self
    {
        return new self(
            accountId: $accountId,
            type: TransactionTypeEnum::DEBIT->value,
            debit: $amount,
            credit: 0.0,
            description: $description
        );
    }

    public static function fromCredit(int $accountId, float $amount, ?string $description = null): self
    {
        return new self(
            accountId: $accountId,
            type: TransactionTypeEnum::CREDIT->value,
            debit: 0.0,
            credit: $amount,
            description: $description
        );
    }

    public static function fromReversal(AccountVoucherLine $line, string $description): self
    {
        $invertedType = $line->type === TransactionTypeEnum::DEBIT->value
            ? TransactionTypeEnum::CREDIT->value
            : TransactionTypeEnum::DEBIT->value;

        return new self(
            accountId: $line->account_id,
            type: $invertedType,
            debit: (float) round($line->credit, 2),  // Invert balances safely
            credit: (float) round($line->debit, 2),  // Invert balances safely
            description: $description
        );
    }

    /**
     * Prepare line payload for database insertion
     */
    public function toLinePayload(int $voucherId, int $slNo): array
    {
        return [
            'voucher_id' => $voucherId,
            'account_id' => $this->accountId,
            'type' => $this->type,
            'debit' => round($this->debit, 2),
            'credit' => round($this->credit, 2),
            'sl_no' => $slNo,
            'description' => $this->description,
            'created_at' => now(),
            'updated_at' => now(),
        ];
    }

    /**
     * Get total debit amount
     */
    public function getDebit(): float
    {
        return $this->debit;
    }

    /**
     * Get total credit amount
     */
    public function getCredit(): float
    {
        return $this->credit;
    }
}
