import { Injectable, ConflictException, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../../common/prisma.service';
import { HoldSeatsDto } from './seats.dto';
import { Cron, CronExpression } from '@nestjs/schedule';
import { SegmentsService } from '../segments/segments.service';

@Injectable()
export class SeatsService {
  constructor(
    private prisma: PrismaService,
    private segmentsService: SegmentsService,
  ) {}

  // ── Seat Map ──────────────────────────────────────────────────────────────
  async getSeatMap(scheduleId: string, coachId?: string) {
    const assignments = await this.prisma.coachAssignment.findMany({
      where: { scheduleId, ...(coachId ? { coachId } : {}) },
      include: { coach: { include: { seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] }, seatClass: true } } },
      orderBy: { positionNumber: 'asc' },
    });

    const allSeatIds = assignments.flatMap(a => a.coach.seats.map(s => s.id));
    const effectiveStatuses = await this.resolveEffectiveStatuses(scheduleId, allSeatIds);

    return {
      coaches: assignments.map((a) => ({
        id: a.coach.id,
        assignmentId: a.id,
        name: `Coach ${a.coach.label}`,
        seatClass: a.coach.seatClass.name,
        positionNumber: a.positionNumber,
        seats: a.coach.seats.map((s) => ({
          id: s.id,
          number: s.label,
          status: effectiveStatuses.get(s.id) ?? s.status,
          kind: s.kind,
          row: s.row,
          col: s.col,
          isWindow: s.isWindow,
          isAisle: s.isAisle,
          bedPosition: s.bedPosition,
        })),
      })),
    };
  }

  /**
   * Computes the effective seat status for a set of seats on a specific schedule
   * by checking active SeatHolds and confirmed JourneySegments.
   *
   * Priority: BLOCKED (physical) > BOOKED (confirmed journey) > HELD (active hold) > AVAILABLE
   *
   * This is needed because seat.status is no longer written during booking —
   * availability is segment-scoped, so the DB column stays AVAILABLE even when held.
   */
  async resolveEffectiveStatuses(
    scheduleId: string,
    seatIds: string[],
  ): Promise<Map<string, string>> {
    const statusMap = new Map<string, string>();

    if (seatIds.length === 0) return statusMap;

    // 1. Active holds — any seat in an unexpired SeatHold for this schedule is HELD
    const activeHolds = await this.prisma.seatHold.findMany({
      where: {
        scheduleId,
        expiresAt: { gt: new Date() },
        seatIds: { hasSome: seatIds },
      },
      select: { seatIds: true },
    });
    for (const hold of activeHolds) {
      for (const seatId of hold.seatIds) {
        if (seatIds.includes(seatId)) statusMap.set(seatId, 'HELD');
      }
    }

    // 2. Active bookings via JourneySegment — CONFIRMED or PENDING_PAYMENT → BOOKED
    //    (overwrites HELD if the same seat has a confirmed booking)
    const bookedSegments = await this.prisma.journeySegment.findMany({
      where: {
        scheduleId,
        seatId: { in: seatIds },
        journey: { status: { in: ['CONFIRMED', 'PENDING_PAYMENT'] } },
      },
      select: { seatId: true },
    });
    for (const seg of bookedSegments) {
      if (seg.seatId) statusMap.set(seg.seatId, 'BOOKED');
    }

    return statusMap;
  }

  // ── Hold / Release ────────────────────────────────────────────────────────
  async holdSeats(dto: HoldSeatsDto) {
    // ── Validate request integrity ───────────────────────────────────────────
    const passengerIds = dto.passengers.map(p => p.passengerId);
    const seatIds      = dto.passengers.map(p => p.seatId);

    if (new Set(passengerIds).size !== passengerIds.length)
      throw new BadRequestException('Duplicate passengerId in passengers list — each passenger must appear once');
    if (new Set(seatIds).size !== seatIds.length)
      throw new BadRequestException('Duplicate seatId in passengers list — each seat can only be assigned to one passenger');

    const expiresAt = new Date(Date.now() + 5 * 60 * 1000);

    const hold = await this.prisma.$transaction(async (tx) => {
      // ── 1. Validate seats exist and none are BLOCKED ─────────────────────
      const seats = await tx.seat.findMany({
        where: { id: { in: seatIds } },
        select: { id: true, status: true, label: true },
      });

      if (seats.length !== seatIds.length) {
        const found = new Set(seats.map(s => s.id));
        const missing = seatIds.filter(id => !found.has(id));
        throw new NotFoundException(`Seat(s) not found: ${missing.join(', ')}`);
      }

      const blocked = seats.filter(s => s.status === 'BLOCKED');
      if (blocked.length > 0)
        throw new ConflictException(`Seat(s) ${blocked.map(s => s.label).join(', ')} are blocked`);

      const seatLabelById = Object.fromEntries(seats.map(s => [s.id, s.label]));

      // ── 2. Resolve requested leg sequences ──────────────────────────────
      const stopTimes = await tx.tripStopTime.findMany({
        where: { scheduleId: dto.scheduleId },
        select: { stationId: true, sequence: true },
      });
      const seqOf = (stationId: string) =>
        stopTimes.find(s => s.stationId === stationId)?.sequence;

      const reqFrom = seqOf(dto.originStationId);
      const reqTo   = seqOf(dto.destinationStationId);

      if (reqFrom === undefined || reqTo === undefined)
        throw new BadRequestException('Origin or destination station not found on this schedule');
      if (reqFrom >= reqTo)
        throw new BadRequestException('Origin must come before destination');

      // ── 3. Load active holds for this schedule ───────────────────────────
      const activeHolds = await tx.seatHold.findMany({
        where: { scheduleId: dto.scheduleId, expiresAt: { gt: new Date() } },
        select: { seatIds: true, createdBy: true },
      });

      // Parse each hold's leg range and passenger list
      const parsedHolds: { seatIds: string[]; from: number; to: number; passengerIds: string[] }[] = [];
      for (const h of activeHolds) {
        try {
          if (h.createdBy?.trimStart().startsWith('{')) {
            const meta = JSON.parse(h.createdBy);
            const holdFrom = seqOf(meta.originStationId);
            const holdTo   = seqOf(meta.destinationStationId);
            if (holdFrom !== undefined && holdTo !== undefined) {
              parsedHolds.push({
                seatIds:      h.seatIds,
                from:         holdFrom,
                to:           holdTo,
                passengerIds: (meta.passengers ?? []).map((p: any) => p.passengerId),
              });
            }
          }
        } catch { /* ignore malformed */ }
      }

      // ── 4. Per-passenger validation with overlap check ───────────────────
      for (const { passengerId, seatId } of dto.passengers) {
        for (const hold of parsedHolds) {
          const legsOverlap = hold.from < reqTo && reqFrom < hold.to;
          if (!legsOverlap) continue; // non-overlapping leg — no conflict

          // Rule A: seat is held on an overlapping leg
          if (hold.seatIds.includes(seatId)) {
            throw new ConflictException(
              `Seat ${seatLabelById[seatId]} is already held for this leg. Please choose a different seat.`,
            );
          }

          // Rule B: passenger already holds a seat on an overlapping leg
          if (hold.passengerIds.includes(passengerId)) {
            throw new ConflictException(
              `Passenger already holds a seat on this journey leg. You can only hold one seat per journey.`,
            );
          }
        }
      }

      // Store passenger→seat mapping AND leg in createdBy as JSON
      const holdMeta = {
        originStationId:      dto.originStationId,
        destinationStationId: dto.destinationStationId,
        passengers: dto.passengers.map(p => ({ passengerId: p.passengerId, seatId: p.seatId })),
      };

      return tx.seatHold.create({
        data: {
          scheduleId:  dto.scheduleId,
          passengerId: dto.passengers[0].passengerId,
          seatIds,
          createdBy:   JSON.stringify(holdMeta),
          expiresAt,
        },
      });
    });

    return this.enrichHold(hold);
  }

  async getHolds(scheduleId?: string, passengerId?: string) {
    const holds = await this.prisma.seatHold.findMany({
      where: {
        expiresAt: { gt: new Date() },
        ...(scheduleId  ? { scheduleId }  : {}),
        ...(passengerId ? { passengerId } : {}),
      },
      orderBy: { createdAt: 'desc' },
    });
    return Promise.all(holds.map(h => this.enrichHold(h)));
  }

  async getHold(holdId: string) {
    const hold = await this.prisma.seatHold.findUnique({ where: { id: holdId } });
    if (!hold) throw new NotFoundException('Hold not found');
    return this.enrichHold(hold);
  }

  /**
   * Resolves the opaque fareQuoteId leg encoding into human-readable station
   * names and enriches the hold with schedule, seat, and leg details.
   */
  private async enrichHold(hold: any) {
    // Decode leg and passenger→seat mapping from createdBy JSON
    let originStationId: string | null = null;
    let destinationStationId: string | null = null;
    let passengerSeatMap: { passengerId: string; seatId: string }[] = [];

    try {
      if (hold.createdBy) {
        const raw = hold.createdBy;
        // Guard: only parse if it looks like a JSON object, not a plain number/string
        if (typeof raw === 'string' && raw.trimStart().startsWith('{')) {
          const meta = JSON.parse(raw);
          originStationId      = meta.originStationId      ?? null;
          destinationStationId = meta.destinationStationId ?? null;
          passengerSeatMap     = Array.isArray(meta.passengers) ? meta.passengers : [];
        }
      }
    } catch { /* ignore malformed createdBy */ }

    const seatIds = hold.seatIds as string[];

    const [schedule, originStation, destinationStation, seats] = await Promise.all([
      this.prisma.trainSchedule.findUnique({
        where: { id: hold.scheduleId },
        include: { train: true, originStation: true, destinationStation: true },
      }),
      originStationId      ? this.prisma.station.findUnique({ where: { id: originStationId } })      : null,
      destinationStationId ? this.prisma.station.findUnique({ where: { id: destinationStationId } }) : null,
      this.prisma.seat.findMany({
        where: { id: { in: seatIds } },
        include: { coach: { include: { seatClass: true } } },
      }),
    ]);

    let originSequence: number | null = null;
    let destinationSequence: number | null = null;
    if (originStationId && destinationStationId) {
      const stopTimes = await this.prisma.tripStopTime.findMany({
        where: { scheduleId: hold.scheduleId, stationId: { in: [originStationId, destinationStationId] } },
        select: { stationId: true, sequence: true },
      });
      originSequence      = stopTimes.find(s => s.stationId === originStationId)?.sequence      ?? null;
      destinationSequence = stopTimes.find(s => s.stationId === destinationStationId)?.sequence ?? null;
    }

    // Build seat map keyed by seatId for quick lookup
    const seatById = Object.fromEntries(seats.map(s => [s.id, s]));

    // Merge passenger→seat mapping with seat details
    const passengers = passengerSeatMap.length > 0
      ? passengerSeatMap.map(({ passengerId, seatId }) => {
          const s = seatById[seatId];
          return {
            passengerId,
            seat: s ? {
              id:         s.id,
              label:      s.label,
              seatNumber: s.seatNumber,
              coach:      s.coach.label,
              seatClass:  s.coach.seatClass.name,
              row:        s.row,
              col:        s.col,
            } : { id: seatId },
          };
        })
      // Fallback for holds created before this change
      : seatIds.map(seatId => {
          const s = seatById[seatId];
          return {
            passengerId: hold.passengerId,
            seat: s ? {
              id:         s.id,
              label:      s.label,
              seatNumber: s.seatNumber,
              coach:      s.coach.label,
              seatClass:  s.coach.seatClass.name,
              row:        s.row,
              col:        s.col,
            } : { id: seatId },
          };
        });

    return {
      holdId:     hold.id,
      expiresAt:  hold.expiresAt,
      createdAt:  hold.createdAt,
      ttlSeconds: Math.max(0, Math.floor((hold.expiresAt.getTime() - Date.now()) / 1000)),
      schedule: schedule ? {
        id:                   schedule.id,
        trainNumber:          schedule.train.number,
        trainName:            schedule.train.name,
        departureAt:          schedule.departureAt,
        arrivalAt:            schedule.arrivalAt,
        fullRouteOrigin:      schedule.originStation.name,
        fullRouteDestination: schedule.destinationStation.name,
      } : null,
      leg: {
        originStationId,
        originStationName:      originStation?.name ?? null,
        originStationCode:      originStation?.code ?? null,
        originSequence,
        destinationStationId,
        destinationStationName: destinationStation?.name ?? null,
        destinationStationCode: destinationStation?.code ?? null,
        destinationSequence,
      },
      passengers,
    };
  }

  async releaseHold(holdId: string) {
    const hold = await this.prisma.seatHold.findUnique({ where: { id: holdId } });
    if (!hold) throw new NotFoundException('Hold not found');
    await this.prisma.seatHold.delete({ where: { id: holdId } });
    return { released: true, holdId };
  }

  async confirmSeats(seatIds: string[]) {
    // No-op for status — availability is segment-scoped via JourneySegment
    // seat.status = BLOCKED is the only hard gate; BOOKED is not used as a booking flag
  }
  async releaseSeats(seatIds: string[]) {
    // Only reset seats that are physically BLOCKED back to AVAILABLE if needed
    // For segment-based bookings, releasing is handled by JourneySegment deletion
  }

  async autoAssignSeats(scheduleId: string, count: number, seatClassName: string, eligibility?: string): Promise<string[]> {
    const seats = await this.prisma.seat.findMany({
      where: {
        coach: { seatClass: { name: seatClassName }, assignments: { some: { scheduleId } } },
        status: 'AVAILABLE',
        ...(eligibility ? { eligibility } : {}),
      },
      orderBy: [{ coach: { label: 'asc' } }, { row: 'asc' }, { col: 'asc' }],
    });

    if (seats.length < count) {
      throw new ConflictException(`Only ${seats.length} seats available, requested ${count}`);
    }

    const assigned = this.findContiguousSeats(seats, count);
    return assigned.map((s) => s.id);
  }

  private findContiguousSeats(seats: any[], count: number): any[] {
    if (count === 1) return [seats[0]];

    const grouped = new Map<string, any[]>();
    for (const seat of seats) {
      const key = `${seat.coachId}-${seat.row}`;
      if (!grouped.has(key)) grouped.set(key, []);
      grouped.get(key)!.push(seat);
    }

    for (const rowSeats of grouped.values()) {
      if (rowSeats.length >= count) {
        return rowSeats.slice(0, count);
      }
    }

    return seats.slice(0, count);
  }

  async exportSeatsCSV(scheduleId: string): Promise<string> {
    const assignments = await this.prisma.coachAssignment.findMany({
      where: { scheduleId },
      include: { coach: { include: { seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] } } } },
    });
    const rows = ['coachId,coachLabel,row,col,label,kind,status,premiumFeeMinor,eligibility'];
    for (const a of assignments) {
      for (const seat of a.coach.seats) {
        rows.push(`${a.coach.id},${a.coach.label},${seat.row},${seat.col},${seat.label},${seat.kind},${seat.status},${seat.premiumFeeMinor},${seat.eligibility || ''}`);
      }
    }
    return rows.join('\n');
  }

  async previewSeatsCSV(csvContent: string): Promise<{ valid: number; invalid: number; errors: string[] }> {
    const lines = csvContent.trim().split('\n').slice(1);
    const errors: string[] = [];
    let valid = 0;
    let invalid = 0;

    for (let i = 0; i < lines.length; i++) {
      const parts = lines[i].split(',');
      if (parts.length < 8) {
        errors.push(`Line ${i + 2}: Invalid format`);
        invalid++;
        continue;
      }
      const [coachId, coachLabel, row, col, label, kind, status, premiumFeeMinor] = parts;
      if (!coachId || !row || !col || !label) {
        errors.push(`Line ${i + 2}: Missing required fields`);
        invalid++;
        continue;
      }
      valid++;
    }

    return { valid, invalid, errors: errors.slice(0, 10) };
  }

  async importSeatsCSV(scheduleId: string, csvContent: string, commit: boolean): Promise<{ imported: number; errors: string[] }> {
    const lines = csvContent.trim().split('\n').slice(1);
    const errors: string[] = [];
    let imported = 0;

    if (!commit) {
      return { imported: 0, errors: ['Preview mode - use commit=true to apply changes'] };
    }

    for (let i = 0; i < lines.length; i++) {
      try {
        const parts = lines[i].split(',');
        const [coachId, coachLabel, row, col, label, kind, status, premiumFeeMinor, eligibility] = parts;

        await this.prisma.seat.upsert({
          where: { coachId_row_col: { coachId, row: parseInt(row), col } },
          update: {
            label,
            kind: kind as any,
            status: status as any,
            premiumFeeMinor: parseInt(premiumFeeMinor) || 0,
            eligibility: eligibility || null,
          },
          create: {
            coachId,
            row: parseInt(row),
            col,
            label,
            kind: kind as any,
            status: status as any,
            premiumFeeMinor: parseInt(premiumFeeMinor) || 0,
            eligibility: eligibility || null,
          },
        });
        imported++;
      } catch (err) {
        errors.push(`Line ${i + 2}: ${err instanceof Error ? err.message : String(err)}`);
      }
    }

    return { imported, errors: errors.slice(0, 10) };
  }

  @Cron(CronExpression.EVERY_MINUTE)
  async expireHolds() {
    const expired = await this.prisma.seatHold.findMany({ where: { expiresAt: { lt: new Date() } } });
    for (const hold of expired) { await this.releaseSeats(hold.seatIds); await this.prisma.seatHold.delete({ where: { id: hold.id } }); }
  }
}
