<?php

namespace App\Livewire\Auth;

use App\Contracts\AuthServiceInterface;
use App\DTO\ChangePasswordDTO;
use Livewire\Component;

class ForceChangePassword extends Component
{
    public string $current_password = '';
    public string $new_password = '';
    public string $new_password_confirmation = '';

    protected function rules(): array
    {
        return [
            'current_password' => ['required', 'string'],
            'new_password' => ['required', 'string', 'min:8', 'confirmed', 'different:current_password'],
        ];
    }

    protected function messages(): array
    {
        return [
            'current_password.required' => 'Password saat ini wajib diisi.',
            'new_password.required' => 'Password baru wajib diisi.',
            'new_password.min' => 'Password baru minimal 8 karakter.',
            'new_password.confirmed' => 'Konfirmasi password baru tidak cocok.',
            'new_password.different' => 'Password baru harus berbeda dari password saat ini.',
        ];
    }

    public function changePassword(AuthServiceInterface $authService)
    {
        $this->validate();

        try {
            $user = auth()->user();
            $changePasswordDTO = ChangePasswordDTO::fromArray([
                'current_password' => $this->current_password,
                'new_password' => $this->new_password,
            ]);

            $authService->changePassword($user, $changePasswordDTO);

            session()->flash('success', 'Password Anda berhasil diperbarui. Selamat datang di sistem!');
            return redirect()->route('dashboard');

        } catch (\Illuminate\Validation\ValidationException $e) {
            foreach ($e->errors() as $field => $messages) {
                foreach ($messages as $message) {
                    $this->addError($field, $message);
                }
            }
        }
    }

    public function render()
    {
        return view('livewire.auth.force-change-password')
            ->layout('components.layouts.guest');
    }
}
