<template>
  <q-page class="flex flex-center">
    <q-card style="width:420px; max-width:90vw">
      <q-card-section>
        <div class="text-h6">Şifre Yenileme Zorunlu</div>
        <div class="text-caption text-grey-7 q-mt-xs">
          Sistemi kullanabilmek için yeni bir şifre belirlemelisiniz.
        </div>
      </q-card-section>

      <q-card-section class="q-gutter-md">
        <q-input
          v-model="currentPassword"
          type="password"
          label="Mevcut Şifre"
          outlined
          dense
        />

        <q-input
          v-model="newPassword"
          type="password"
          label="Yeni Şifre"
          outlined
          dense
        />

        <q-input
          v-model="newPassword2"
          type="password"
          label="Yeni Şifre (Tekrar)"
          outlined
          dense
        />

        <q-banner
          v-if="error"
          class="bg-red-1 text-red q-mt-sm"
          rounded
        >
          {{ error }}
        </q-banner>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn
          label="Kaydet"
          color="primary"
          :loading="loading"
          @click="submit"
        />
      </q-card-actions>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from 'src/services/api'
import { useAuthStore } from 'stores/authStore.js'
import { usePermission } from 'src/composables/usePermission'

const { canRead, canWrite, canUpdate } = usePermission()

const canReadOrder   = canRead('order')
const canWriteOrder  = canWrite('order')
const canUpdateOrder = canUpdate('order')

const router = useRouter()
const auth = useAuthStore()

const currentPassword = ref('')
const newPassword = ref('')
const newPassword2 = ref('')
const loading = ref(false)
const error = ref('')

async function submit () {
  error.value = ''

  if (!currentPassword.value || !newPassword.value || !newPassword2.value) {
    error.value = 'Tüm alanlar zorunludur'
    return
  }

  if (newPassword.value !== newPassword2.value) {
    error.value = 'Yeni şifreler eşleşmiyor'
    return
  }

  loading.value = true
  try {
    // 🔐 TOKEN interceptor ile otomatik
    const res = await api.post('/password/change', {
      current_password: currentPassword.value,
      new_password: newPassword.value
    })

    // 🔄 Session güncelle
    auth.setSession(res.data)
    auth.forcePasswordChange = false
    localStorage.setItem('forcePasswordChange', '0')

    router.replace('/app')

  } catch (e) {
    error.value =
      e?.data?.message ||
      e?.message ||
      'Şifre güncellenemedi'
  } finally {
    loading.value = false
  }
}
</script>




