import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateShippingLineDto } from '../dto/create-shipping-line.dto';
import { UpdateShippingLineDto } from '../dto/update-shipping-line.dto';
import { ShippingLine } from '../entities/shipping-line.entity';
import {
  IShippingLinesRepository,
  SHIPPING_LINES_REPOSITORY,
} from '../interfaces/shipping-lines.repository.interface';

@Injectable()
export class ShippingLinesService {
  constructor(
    @Inject(SHIPPING_LINES_REPOSITORY)
    private readonly repository: IShippingLinesRepository,
  ) {}

  /** List shipping lines with pagination. */
  async findAll(filter: {
    isActive?: boolean;
    page?: number;
    pageSize?: number;
  }): Promise<{ data: ShippingLine[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
    const page = filter.page ?? 1;
    const pageSize = filter.pageSize ?? 20;
    const where: Record<string, unknown> = {};
    if (filter.isActive !== undefined) where.isActive = filter.isActive;

    const [data, total] = await this.repository.findAndCount({
      where,
      order: { code: 'ASC' },
      skip: (page - 1) * pageSize,
      take: pageSize,
    });
    return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
  }

  /** Get a shipping line by ID. */
  async findById(id: string): Promise<ShippingLine> {
    const entity = await this.repository.findById(id);
    if (!entity) throw new NotFoundException(`Shipping line ${id} not found`);
    return entity;
  }

  /** Create a shipping line. */
  async create(dto: CreateShippingLineDto): Promise<ShippingLine> {
    const existing = await this.repository.findByCode(dto.code);
    if (existing) throw new ConflictException(`Shipping line with code "${dto.code}" already exists`);
    return this.repository.create({
      code: dto.code,
      label: dto.label,
      mappedToCode: dto.mappedToCode,
      showExtraFeeNotice: dto.showExtraFeeNotice ?? false,
      isActive: dto.isActive ?? true,
    });
  }

  /** Update a shipping line. */
  async update(id: string, dto: UpdateShippingLineDto): Promise<ShippingLine> {
    await this.findById(id);
    if (dto.code) {
      const conflict = await this.repository.findByCode(dto.code);
      if (conflict && conflict.id !== id) {
        throw new ConflictException(`Shipping line with code "${dto.code}" already exists`);
      }
    }
    const updated = await this.repository.update(id, dto);
    if (!updated) throw new NotFoundException(`Shipping line ${id} not found`);
    return updated;
  }

  /** Soft-delete a shipping line. */
  async remove(id: string): Promise<void> {
    await this.findById(id);
    await this.repository.softDelete(id);
  }
}
