'use strict';

const {
  makeParticipant,
  startEncounter,
  applyHpChange,
  deathSave,
  stabilizeParticipant,
  reviveParticipant,
} = require('@ttrpg/shared');
const { mockCtx } = require('./_helpers');

function pc(id, extra = {}) {
  return makeParticipant({
    id,
    name: id,
    type: 'character',
    initiative: 10,
    maxHp: 100,
    currentHp: 100,
    ...extra,
  });
}
function monster(id, extra = {}) {
  return makeParticipant({
    id,
    name: id,
    type: 'monster',
    initiative: 10,
    maxHp: 100,
    currentHp: 100,
    ...extra,
  });
}

function enc(participants, extra = {}) {
  return {
    id: 'e1',
    name: 'death-save-test',
    participants,
    isStarted: false,
    isPaused: false,
    round: 0,
    currentTurnParticipantId: null,
    turnOrderIds: [],
    ...extra,
  };
}

async function startedAtZero() {
  const { ctx } = mockCtx();
  let e = enc([pc('a')]);
  e = await startEncounter(e, ctx);
  const originalTurnOrderIds = [...e.turnOrderIds];
  e = await applyHpChange(e, 'a', 'damage', 100, ctx);
  return { e, ctx, originalTurnOrderIds };
}

const part = e => e.participants.find(p => p.id === 'a');

describe('death saves: D&D 5e status state machine', () => {
  test('damage drops character to dying without removal or deactivation', async () => {
    const { e, originalTurnOrderIds } = await startedAtZero();
    const p = part(e);

    expect(p.currentHp).toBe(0);
    expect(p.status).toBe('dying');
    expect(p.deathSaveSuccesses).toBe(0);
    expect(p.deathSaveFailures).toBe(0);
    expect(p.isActive).not.toBe(false);
    expect(e.participants.map(x => x.id)).toContain('a');
    expect(e.turnOrderIds).toEqual(originalTurnOrderIds);
  });

  test('damage drops non-NPC monster to dead/inactive, not dying', async () => {
    const { ctx } = mockCtx();
    let e = enc([monster('a')]);
    e = await startEncounter(e, ctx);
    const orderBefore = [...e.turnOrderIds];

    e = await applyHpChange(e, 'a', 'damage', 100, ctx);

    expect(part(e).status).toBe('dead');
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
    expect(part(e).conditions).not.toContain('unconscious');
    expect(part(e).isActive).toBe(false);
    expect(e.turnOrderIds).toEqual(orderBefore);
  });

  test('dead non-NPC monster with stale active flag repairs to inactive', async () => {
    const { ctx } = mockCtx();
    let e = enc([monster('a', { currentHp: 0, status: 'dead', isActive: true })]);
    e = await startEncounter(e, ctx);

    e = await applyHpChange(e, 'a', 'damage', 1, ctx);

    expect(part(e).status).toBe('dead');
    expect(part(e).isActive).toBe(false);
  });

  test('damage drops NPC to dying', async () => {
    const { ctx } = mockCtx();
    let e = enc([monster('a', { type: 'npc' })]);
    e = await startEncounter(e, ctx);

    e = await applyHpChange(e, 'a', 'damage', 100, ctx);

    expect(part(e).type).toBe('npc');
    expect(part(e).status).toBe('dying');
    expect(part(e).conditions).toContain('unconscious');
  });

  test('three failures immediately makes dead, resets counters, keeps participant and turn order', async () => {
    let { e, ctx, originalTurnOrderIds } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(1);

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(2);

    const res = await deathSave(e, 'a', 'fail', ctx);
    e = res.enc;
    expect(res.status).toBe('dead');
    expect(part(e).status).toBe('dead');
    expect(part(e).currentHp).toBe(0);
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
    expect(part(e).isActive).not.toBe(false);
    expect(e.participants.map(x => x.id)).toContain('a');
    expect(e.turnOrderIds).toEqual(originalTurnOrderIds);
  });

  test('three successes immediately makes stable and resets counters', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    const res = await deathSave(e, 'a', 'success', ctx);
    e = res.enc;

    expect(res.status).toBe('stable');
    expect(part(e).status).toBe('stable');
    expect(part(e).currentHp).toBe(0);
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('successes and failures are independent before terminal transition', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;

    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(2);
    expect(part(e).deathSaveSuccesses).toBe(2);

    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    expect(part(e).status).toBe('stable');
    expect(part(e).deathSaveFailures).toBe(0);
    expect(part(e).deathSaveSuccesses).toBe(0);
  });

  test('nat1 adds two failures and can kill', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'nat1', ctx)).enc;
    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(2);

    e = (await deathSave(e, 'a', 'nat1', ctx)).enc;
    expect(part(e).status).toBe('dead');
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('nat1 at one failure immediately kills', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'nat1', ctx)).enc;

    expect(part(e).status).toBe('dead');
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('nat20 restores to 1 HP conscious and resets counters', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'nat20', ctx)).enc;

    expect(part(e).status).toBe('conscious');
    expect(part(e).currentHp).toBe(1);
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('damage while dying adds one failure', async () => {
    let { e, ctx } = await startedAtZero();

    e = await applyHpChange(e, 'a', 'damage', 1, ctx);

    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(1);
  });

  test('critical damage while dying adds two failures', async () => {
    let { e, ctx } = await startedAtZero();

    e = await applyHpChange(e, 'a', 'damage', 1, { isCriticalHit: true }, ctx);

    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveFailures).toBe(2);
  });

  test('damage while stable returns to dying and applies failure', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    expect(part(e).status).toBe('stable');

    e = await applyHpChange(e, 'a', 'damage', 1, ctx);

    expect(part(e).status).toBe('dying');
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(1);
  });

  test('healing while dying or stable makes conscious and clears counters', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = await applyHpChange(e, 'a', 'heal', 10, ctx);
    expect(part(e).status).toBe('conscious');
    expect(part(e).currentHp).toBe(10);
    expect(part(e).deathSaveFailures).toBe(0);

    e = await applyHpChange(e, 'a', 'damage', 10, ctx);
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    e = (await deathSave(e, 'a', 'success', ctx)).enc;
    expect(part(e).status).toBe('stable');

    e = await applyHpChange(e, 'a', 'heal', 5, ctx);
    expect(part(e).status).toBe('conscious');
    expect(part(e).currentHp).toBe(5);
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('normal healing does not revive dead', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    expect(part(e).status).toBe('dead');

    try { e = await applyHpChange(e, 'a', 'heal', 10, ctx); } catch (err) {}

    expect(part(e).status).toBe('dead');
    expect(part(e).currentHp).toBe(0);
  });

  test('stabilize sets stable, hp zero, counters zero', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = await stabilizeParticipant(e, 'a', ctx);

    expect(part(e).status).toBe('stable');
    expect(part(e).currentHp).toBe(0);
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
  });

  test('negative heal acts as damage and can drop to dying', async () => {
    const { ctx } = mockCtx();
    let e = enc([pc('a', { currentHp: 1 })]);
    e = await startEncounter(e, ctx);

    e = await applyHpChange(e, 'a', 'heal', -1, ctx);

    expect(part(e).currentHp).toBe(0);
    expect(part(e).status).toBe('dying');
  });

  test('negative damage acts as healing', async () => {
    let { e, ctx } = await startedAtZero();

    e = await applyHpChange(e, 'a', 'damage', -5, ctx);

    expect(part(e).currentHp).toBe(5);
    expect(part(e).status).toBe('conscious');
  });

  test('revive moves dead participant to 0 HP stable/unconscious', async () => {
    let { e, ctx } = await startedAtZero();

    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    e = (await deathSave(e, 'a', 'fail', ctx)).enc;
    expect(part(e).status).toBe('dead');

    e = await reviveParticipant(e, 'a', ctx);

    expect(part(e).currentHp).toBe(0);
    expect(part(e).status).toBe('stable');
    expect(part(e).deathSaveSuccesses).toBe(0);
    expect(part(e).deathSaveFailures).toBe(0);
    expect(part(e).conditions).toContain('unconscious');
    expect(part(e).isActive).toBe(true);
  });

  test('death save outside dying state is rejected or no-op', async () => {
    const { ctx } = mockCtx();
    let e = enc([pc('a')]);
    e = await startEncounter(e, ctx);

    try { e = (await deathSave(e, 'a', 'fail', ctx)).enc; } catch (err) {}

    expect(part(e).status).toBe('conscious');
    expect(part(e).deathSaveFailures).toBe(0);
  });
});
