/**
 * Data Handlers
 * Handles data export (GDPR), statistics, and account deletion
 */

import type { PlayerSession } from '../game/PlayerSession.js';
import { getPlayerStatistics, getPhotoAlbum } from '../services/retention/index.js';
import { resolvePayloadField } from './payloadHelpers.js';

export async function handleExportData(payload: unknown, session: PlayerSession): Promise<void> {
  const player = session.player;

  try {
    // Gather all player data
    const statistics = getPlayerStatistics(player.userId);
    const photoAlbum = getPhotoAlbum(player.userId);

    // Build export data structure matching Python format
    const exportData = {
      metadata: {
        exportDate: new Date().toISOString(),
        playerId: player.userId,
      },
      character: {
        id: player.c.id,
        firstname: player.c.firstname,
        lastname: player.c.lastname,
        sex: player.c.sex,
        ageYears: player.c.ageYears,
        ageDays: player.c.ageDays,
        birthday: player.c.birthday,
        status: player.c.status,
        mood: player.c.mood,
        health: player.c.health,
        energy: player.c.energy,
        happiness: player.c.happiness,
        intelligence: player.c.intelligence,
        prestige: player.c.prestige,
        money: player.c.money,
        diamonds: player.c.diamonds,
        occupation: player.c.occupation,
        education: player.c.education,
        location: player.c.location,
        interests: player.c.interests,
        traits: player.c.traits,
      },
      relationships: player.r.map((p) => ({
        id: p.id,
        firstname: p.firstname,
        lastname: p.lastname,
        relationships: p.relationships,
        affinity: p.affinity,
      })),
      statistics,
      photoAlbum,
      gameState: {
        date: player.date,
        time: player.time,
        season: player.season,
        gameSpeed: player.gameSpeed,
        status: player.status,
      },
    };

    // Python format: {'type': 'dataExportComplete', 'data': export_data}
    session.send({
      type: 'dataExportComplete',
      data: exportData,
    });
  } catch (error) {
    console.error(`Error exporting data for player ${player.userId}:`, error);
    session.send({
      type: 'error',
      error_code: 'EXPORT_FAILED',
      message: error instanceof Error ? error.message : 'Failed to export data',
    });
  }
}

export async function handleGetStatistics(
  _payload: unknown,
  session: PlayerSession
): Promise<void> {
  const player = session.player;

  const statistics = getPlayerStatistics(player.userId);

  // Spread statistics at root level like Python
  session.send({
    type: 'playerStatistics',
    ...statistics,
  });
}

export async function handleDeleteAccount(
  payload: unknown,
  session: PlayerSession
): Promise<void> {
  const confirmation = resolvePayloadField(payload, 'confirmation');
  const player = session.player;

  // Python: if confirmation != 'DELETE' -> error
  if (confirmation !== 'DELETE') {
    session.send({
      type: 'error',
      error_code: 'INVALID_CONFIRMATION',
      message: 'Must type DELETE to confirm',
    });
    return;
  }

  try {
    // Schedule account deletion (30 days grace period). Persist the marker on
    // the player so it survives save/load; the purge background job permanently
    // deletes accounts once this timestamp is in the past.
    const deletionDate = new Date();
    deletionDate.setDate(deletionDate.getDate() + 30);

    player.deletionScheduledAt = deletionDate.toISOString();
    await session.savePlayer();

    console.log(
      `Account deletion scheduled for player ${player.userId} on ${deletionDate.toISOString()}`
    );

    // Python format: {'type': 'accountDeletionScheduled', 'gracePeriodDays': 30, 'result': result}
    session.send({
      type: 'accountDeletionScheduled',
      gracePeriodDays: 30,
      result: {
        success: true,
        scheduledAt: deletionDate.toISOString(),
      },
    });
  } catch (error) {
    console.error(`Error scheduling account deletion for player ${player.userId}:`, error);
    session.send({
      type: 'error',
      error_code: 'DELETION_FAILED',
      message: error instanceof Error ? error.message : 'Failed to schedule account deletion',
    });
  }
}

export async function handleCancelAccountDeletion(
  _payload: unknown,
  session: PlayerSession
): Promise<void> {
  const player = session.player;

  // Cancel the scheduled deletion: clear the persisted marker and save so the
  // purge job will no longer consider this account.
  player.deletionScheduledAt = null;
  await session.savePlayer();

  console.log(`Account deletion cancelled for player ${player.userId}`);

  session.send({
    type: 'accountDeletionCancelled',
    success: true,
    message: 'Account deletion has been cancelled. Your account will remain active.',
  });
}
