<?php

namespace App\Imports;

use App\Models\Account;
use App\Models\AccountType;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class AccountsImport implements ToModel, WithHeadingRow, WithValidation
{
    protected $companyId;

    public function __construct()
    {
        $this->companyId = Auth::user()->current_company_id;
    }

    public function model(array $row)
    {
        // Lookup the ID based on the string name
        $typeName = trim($row['account_type']);
        $accountType = AccountType::whereRaw('LOWER(name) = ?', [strtolower($typeName)])->first();

        // This only runs if validation passes
        return new Account([
            'company_id'      => $this->companyId,
            'user_id'         => Auth::id(),
            'account_type_id' => $accountType->id,
            'code'            => $row['code'],
            'name'            => $row['name'],
            'is_active'       => true,
        ]);
    }

    public function rules(): array
    {
        return [
            // Ensure the code is unique for THIS company only
            'code' => [
                'required',
                Rule::unique('accounts', 'code')->where(function ($query) {
                    return $query->where('company_id', $this->companyId);
                }),
            ],
            // Ensure the name is unique for THIS company only
            'name' => [
                'required',
                Rule::unique('accounts', 'name')->where(function ($query) {
                    return $query->where('company_id', $this->companyId);
                }),
            ],
            // Ensure the account type actually exists in your DB
            'account_type' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!AccountType::whereRaw('LOWER(name) = ?', [strtolower($value)])->exists()) {
                        $fail("The account type '$value' does not exist in the system.");
                    }
                },
            ],
        ];
    }

    public function customValidationMessages()
    {
        return [
            'code.unique' => 'The account code :input already exists in your Chart of Accounts. The entire upload has been cancelled.',
            'name.unique' => 'The account name :input already exists in your Chart of Accounts. The entire upload has been cancelled.',
        ];
    }
}