import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SaveRoomDecorPlacementDto } from '../../../business/room_decor/dto/save_room_decor_placement.dto';
import { RoomDecorPlacements } from './room_decor_placements.entity';

@Injectable()
export class RoomDecorPlacementsService {
  constructor(
    @InjectRepository(RoomDecorPlacements)
    private readonly placementsRepository: Repository<RoomDecorPlacements>,
  ) {}

  async listPlacements(userId: bigint): Promise<RoomDecorPlacements[]> {
    return await this.placementsRepository.find({
      where: { user_id: userId },
      order: { created_at: 'ASC', id: 'ASC' },
    });
  }

  async savePlacement(userId: bigint, placement: SaveRoomDecorPlacementDto): Promise<RoomDecorPlacements> {
    const decorId = this.normalizeDecorId(placement.decor_id);
    let row = await this.placementsRepository.findOne({
      where: { user_id: userId, decor_id: decorId },
    });
    if (!row) {
      row = new RoomDecorPlacements();
      row.user_id = userId;
      row.decor_id = decorId;
      row.created_at = new Date();
    }
    row.placed = placement.placed;
    row.position_x = placement.placed ? Number(placement.position_x ?? row.position_x ?? 0) : null;
    row.position_y = placement.placed ? Number(placement.position_y ?? row.position_y ?? 0) : null;
    row.scale = Number(placement.scale ?? row.scale ?? 1);
    row.rotation_degrees = Number(placement.rotation_degrees ?? row.rotation_degrees ?? 0);
    row.z_index = Number(placement.z_index ?? row.z_index ?? 0);
    row.updated_at = new Date();
    return await this.placementsRepository.save(row);
  }

  private normalizeDecorId(decorId: string): string {
    const normalized = (decorId || '').trim();
    if (!/^[A-Za-z0-9_:-]{1,100}$/.test(normalized)) {
      throw new BadRequestException('摆件ID格式不正确');
    }
    return normalized;
  }
}
