import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DrawingTemplate } from './drawing-template.entity';
import {
  CreateDrawingTemplateDto,
  UpdateDrawingTemplateDto,
} from './dto/drawing-template.dto';

@Injectable()
export class DrawingTemplatesService {
  constructor(
    @InjectRepository(DrawingTemplate)
    private readonly repo: Repository<DrawingTemplate>,
  ) {}

  create(dto: CreateDrawingTemplateDto): Promise<DrawingTemplate> {
    return this.repo.save(this.repo.create(dto));
  }

  findAll(): Promise<DrawingTemplate[]> {
    return this.repo.find({ order: { name: 'ASC' } });
  }

  findById(id: number): Promise<DrawingTemplate | null> {
    return this.repo.findOne({ where: { id } });
  }

  async update(id: number, dto: UpdateDrawingTemplateDto): Promise<DrawingTemplate> {
    const template = await this.findById(id);
    if (!template) throw new NotFoundException('Drawing template not found');
    Object.assign(template, dto);
    return this.repo.save(template);
  }

  async delete(id: number): Promise<boolean> {
    const result = await this.repo.delete(id);
    return (result.affected || 0) > 0;
  }
}
