import { AppDataSource } from '../config/database';
import { In } from 'typeorm';
import { ScheduledOrder } from '../models/ScheduledOrder';
import { Journey } from '../models/Journey';
import { ScheduledOrderService } from './scheduled-order.service';
import { GangOrderService } from './gang-order.service';
import type { WizardOrderInput } from './order-wizard.service';

const scheduledRepo = () => AppDataSource.getRepository(ScheduledOrder);
const journeyRepo = () => AppDataSource.getRepository(Journey);

export type PlannedActionStrategy = 'at_time' | 'on_arrival';
export type PlannedActionSource = 'scheduled_order' | 'journey';
export type PlannedActionStatus = 'pending' | 'in_progress' | 'executed' | 'failed' | 'cancelled';

/**
 * Format unifié pour les actions planifiées d'un joueur, indépendamment
 * de la table de stockage (scheduled_orders ou journeys). Exposé au
 * frontend pour une vue « Mes actions planifiées » unifiée.
 */
export interface PlannedActionRow {
  id: string;
  source: PlannedActionSource;
  strategy: PlannedActionStrategy;
  order_key: string;
  scope_type: string | null;
  scope_id: string | null;
  scheduled_at: string | null;
  estimated_arrival_at: string | null;
  status: PlannedActionStatus;
  error: string | null;
  created_at: string;
}

/**
 * PlannedActionService — Phase 16 (2026-04-22), unification U5 (soft).
 *
 * Façade unifiée au-dessus de :
 *   - `ScheduledOrderService` (ordres wizard programmés `at_time`)
 *   - `GangOrderService`      (ordres Journey exécutés `on_arrival`)
 *
 * Les 2 tables et leurs CRONs restent en place. Cette façade expose :
 *   - `listAllPending(playerId)`  — merge des 2 sources au format unifié
 *   - `schedule(...)`             — dispatch selon `strategy`
 *   - `cancel(actionId, source)`  — dispatch sur le bon service
 *
 * But : permettre à l'UI de proposer une vue unique sans casser les 2
 * systèmes existants qui ont chacun leur raison d'être (time-based vs
 * position-based).
 */
export class PlannedActionService {
  /**
   * Retourne toutes les actions planifiées pending/in_progress d'un joueur.
   * Format unifié pour le frontend (ordre chronologique croissant).
   */
  static async listAllPending(playerId: string): Promise<PlannedActionRow[]> {
    const [scheduled, journeys] = await Promise.all([
      scheduledRepo().find({
        where: { player_id: playerId, status: 'pending' as any },
        order: { scheduled_at: 'ASC' },
        take: 100,
      }),
      journeyRepo().find({
        where: {
          player_id: playerId,
          status: In(['in_transit', 'arrived']) as any,
        } as any,
        order: { estimated_arrival: 'ASC' } as any,
        take: 100,
      }),
    ]);

    const rows: PlannedActionRow[] = [];

    for (const s of scheduled) {
      rows.push({
        id: s.id,
        source: 'scheduled_order',
        strategy: 'at_time',
        order_key: s.order_key,
        scope_type: s.scope_type ?? null,
        scope_id: s.scope_id ?? null,
        scheduled_at: s.scheduled_at ? new Date(s.scheduled_at).toISOString() : null,
        estimated_arrival_at: null,
        status: s.status as PlannedActionStatus,
        error: (s as any).error ?? null,
        created_at: (s as any).created_at
          ? new Date((s as any).created_at).toISOString()
          : new Date().toISOString(),
      });
    }

    for (const j of journeys) {
      // Ignorer les pur-déplacements (order_type = 'travel' ou absent)
      const orderType = (j as any).order_type;
      if (!orderType || orderType === 'travel') continue;
      rows.push({
        id: j.id,
        source: 'journey',
        strategy: 'on_arrival',
        order_key: orderType,
        scope_type: (j as any).gang_id ? 'gang' : null,
        scope_id: (j as any).gang_id ?? null,
        scheduled_at: null,
        estimated_arrival_at: (j as any).estimated_arrival
          ? new Date((j as any).estimated_arrival).toISOString()
          : null,
        status: ((j as any).status === 'in_transit' ? 'in_progress'
          : (j as any).status === 'arrived' ? 'executed'
          : 'pending') as PlannedActionStatus,
        error: null,
        created_at: (j as any).created_at
          ? new Date((j as any).created_at).toISOString()
          : new Date().toISOString(),
      });
    }

    // Tri par date (scheduled_at ou estimated_arrival_at) ascendant
    rows.sort((a, b) => {
      const aD = a.scheduled_at ?? a.estimated_arrival_at ?? a.created_at;
      const bD = b.scheduled_at ?? b.estimated_arrival_at ?? b.created_at;
      return new Date(aD).getTime() - new Date(bD).getTime();
    });

    return rows;
  }

  /**
   * Programme une action. Si `strategy='at_time'`, passe par ScheduledOrderService.
   * Si `strategy='on_arrival'` + payload.gang_id + payload.order_params, passe par
   * GangOrderService (Journey-based).
   */
  static async schedule(
    playerId: string,
    orderKey: string,
    input: WizardOrderInput,
    strategy: PlannedActionStrategy,
    scheduledAt?: Date,
  ): Promise<{ id: string; source: PlannedActionSource; message: string }> {
    if (strategy === 'at_time') {
      if (!scheduledAt) throw new Error('scheduledAt requis pour strategy=at_time');
      const r = await ScheduledOrderService.schedule(playerId, orderKey, input, scheduledAt);
      return { id: r.id, source: 'scheduled_order', message: r.message };
    }
    // strategy=on_arrival → GangOrderService (requiert gang_id + target coords)
    const gangId = input.scope?.id;
    const target = input.target;
    if (!gangId || !target?.lat || !target?.lng) {
      throw new Error('on_arrival requiert scope.id gang + target.lat/lng');
    }
    const j = await GangOrderService.createOrder({
      gangId,
      memberPlayerId: playerId,
      orderType: orderKey as any,
      destination: { lat: target.lat, lon: target.lng },
      targetType: target.poi_type ?? null,
      targetId: target.poi_id ?? null,
      orderParams: {},
      vehicleId: input.vehicle_ids?.[0],
      requestedBy: playerId,
    });
    return { id: j.id, source: 'journey', message: `Ordre ${orderKey} lancé (on_arrival)` };
  }

  /** Annule une action planifiée, dispatch sur le bon service selon source. */
  static async cancel(
    playerId: string,
    actionId: string,
    source: PlannedActionSource,
  ): Promise<{ success: boolean; message: string }> {
    if (source === 'scheduled_order') {
      return ScheduledOrderService.cancel(actionId, playerId);
    }
    // Journey cancel : déléguer à gang-order handlers existants via route existante
    // (gang/order/:journeyId/cancel). Par simplicité, on permet l'annulation
    // directe en marquant le journey comme cancelled.
    const journey = await journeyRepo().findOne({ where: { id: actionId } });
    if (!journey) return { success: false, message: 'Journey introuvable' };
    if ((journey as any).player_id !== playerId) {
      return { success: false, message: 'Pas votre ordre' };
    }
    if (!['in_transit', 'arrived'].includes((journey as any).status)) {
      return { success: false, message: `Impossible d'annuler un ordre ${(journey as any).status}` };
    }
    (journey as any).status = 'cancelled';
    await journeyRepo().save(journey);
    return { success: true, message: 'Ordre annulé' };
  }
}
