import { test, expect } from '@playwright/test';
import axios from 'axios';
import fs from 'fs';

const BASE_URL = 'https://rumc.dev.rdcenter.ru/api';
const NEW_PASSWORD = '!Test123456';

const user = JSON.parse(fs.readFileSync('temp/user.json', 'utf-8'));

test('API: восстановление пароля', async () => {
  const email = user.email;

  const sendResetRes = await axios.post(`${BASE_URL}/auth/resetPassword?type=reset`, {
    email,
  });
  expect(sendResetRes.status).toBe(201);

  console.log('📬 Письмо с кодом отправлено');

  const { waitForConfirmationCode } = await import('../../../utils/mailTmApi');
  const code = await waitForConfirmationCode(email, user.mailToken, 'recover', 60000);
  expect(code).toMatch(/^\d{6}$/);
  console.log('✅ Код подтверждения:', code);

  const confirmRes = await axios.post(`${BASE_URL}/auth/confirmReset`, {
    email,
    code
  });
  expect(confirmRes.status).toBe(201);
  const resetTokenRaw = confirmRes.data.resetTokenRaw;
  console.log('🔑 Получен resetToken:', resetTokenRaw);

  const recoveryRes = await axios.post(`${BASE_URL}/auth/recovery`, {
    email,
    resetToken: resetTokenRaw,
    passwordReset: NEW_PASSWORD
  });
  expect(recoveryRes.status).toBe(201);

  const accessToken = recoveryRes.data.access_token;
  console.log('🪪 Новый access_token:', accessToken);
});
