<?php

namespace App\Imports;

use App\Models\AccountType;
use App\Models\AccountGroup;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class AccountTypesImport implements ToModel, WithHeadingRow, WithValidation
{
    public function model(array $row)
    {
        $groupName = trim($row['account_group']);
        $group = AccountGroup::whereRaw('LOWER(name) = ?', [strtolower($groupName)])->first();

        return new AccountType([
            'account_group_id' => $group->id,
            'name'             => $row['name'],
            'description'      => $row['description'] ?? null,
        ]);
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255|unique:account_types,name',
            'account_group' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!AccountGroup::whereRaw('LOWER(name) = ?', [strtolower($value)])->exists()) {
                        $fail("The account group '$value' does not exist.");
                    }
                },
            ],
        ];
    }
}