import { Inject } from '@nestjs/common';
import { type ICommandHandler, CommandHandler } from '@nestjs/cqrs';
import { createId } from '@paralleldrive/cuid2';
import { ConflictException } from '@modules/shared';
import { IndustrialParkEntity } from '../../../domain/entities/industrial-park.entity';
import {
  INDUSTRIAL_PARK_REPOSITORY,
  type IIndustrialParkRepository,
} from '../../../domain/repositories/industrial-park.repository';
import { CreateIndustrialParkCommand } from './create-industrial-park.command';

@CommandHandler(CreateIndustrialParkCommand)
export class CreateIndustrialParkHandler implements ICommandHandler<CreateIndustrialParkCommand> {
  constructor(
    @Inject(INDUSTRIAL_PARK_REPOSITORY)
    private readonly repo: IIndustrialParkRepository,
  ) {}

  async execute(cmd: CreateIndustrialParkCommand): Promise<{ id: string }> {
    const existing = await this.repo.findBySlug(cmd.slug);
    if (existing) {
      throw new ConflictException(`Industrial park with slug "${cmd.slug}" already exists`);
    }

    const now = new Date();
    const entity = new IndustrialParkEntity(
      createId(),
      {
        name: cmd.name,
        nameEn: cmd.nameEn,
        slug: cmd.slug,
        developer: cmd.developer,
        operator: cmd.operator,
        status: cmd.status,
        latitude: cmd.latitude,
        longitude: cmd.longitude,
        address: cmd.address,
        district: cmd.district,
        province: cmd.province,
        region: cmd.region,
        totalAreaHa: cmd.totalAreaHa,
        leasableAreaHa: cmd.leasableAreaHa,
        occupancyRate: cmd.occupancyRate,
        remainingAreaHa: cmd.remainingAreaHa,
        tenantCount: cmd.tenantCount,
        establishedYear: cmd.establishedYear,
        landRentUsdM2Year: cmd.landRentUsdM2Year,
        rbfRentUsdM2Month: cmd.rbfRentUsdM2Month,
        rbwRentUsdM2Month: cmd.rbwRentUsdM2Month,
        managementFeeUsd: cmd.managementFeeUsd,
        infrastructure: cmd.infrastructure,
        connectivity: cmd.connectivity,
        incentives: cmd.incentives,
        targetIndustries: cmd.targetIndustries,
        existingTenants: null,
        certifications: null,
        media: null,
        documents: null,
        description: cmd.description,
        descriptionEn: cmd.descriptionEn,
        isVerified: false,
        ownerId: cmd.ownerId,
      },
      now,
      now,
    );

    await this.repo.save(entity);
    return { id: entity.id };
  }
}
