<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class UserKycProfile extends Model
{
    /**
     * @var list<string>
     */
    protected $fillable = [
        'user_id',
        'legal_first_name',
        'legal_last_name',
        'date_of_birth',
        'document_type',
        'document_number',
        'document_issuing_country',
        'country_of_residence',
        'address_line1',
        'address_line2',
        'city',
        'region_state',
        'postal_code',
        'occupation',
        'document_front_path',
        'document_back_path',
        'selfie_document_path',
        'reviewed_at',
        'reviewed_by',
    ];

    /**
     * @return array<string, string|null>
     */
    protected function casts(): array
    {
        return [
            'date_of_birth' => 'date',
            'reviewed_at' => 'datetime',
        ];
    }

    /**
     * @return BelongsTo<User, UserKycProfile>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return BelongsTo<User, UserKycProfile>
     */
    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }

    public function documentTypeLabel(): string
    {
        return match ($this->document_type) {
            'national_id' => 'Documento nacional de identidad',
            'passport' => 'Pasaporte',
            'drivers_license' => 'Licencia de conducir',
            'residence_card' => 'Tarjeta de residencia / permiso migratorio',
            default => (string) $this->document_type,
        };
    }

    public function deleteStoredDocuments(): void
    {
        $disk = Storage::disk('kyc');

        foreach (['document_front_path', 'document_back_path', 'selfie_document_path'] as $attr) {
            $path = $this->{$attr} ?? null;
            if ($path !== null && $path !== '' && $disk->exists($path)) {
                $disk->delete($path);
            }
        }
    }
}
