import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SeoTemplate } from './entities/seo_template.entity';

@Injectable()
export class SeoTemplatesService {
  constructor(
    @InjectRepository(SeoTemplate)
    private readonly seoTemplateRepository: Repository<SeoTemplate>,
  ) {}

  async findAll() {
    return this.seoTemplateRepository.find({
      order: { templateKey: 'ASC' },
    });
  }

  async findByKey(key: string) {
    const template = await this.seoTemplateRepository.findOne({
      where: { templateKey: key, status: 'active' },
    });
    return template;
  }

  async findOne(id: number) {
    const template = await this.seoTemplateRepository.findOne({
      where: { id },
    });
    if (!template)
      throw new NotFoundException(`Template with ID ${id} not found`);
    return template;
  }

  async create(createDto: any) {
    const template = this.seoTemplateRepository.create(createDto);
    return this.seoTemplateRepository.save(template);
  }

  async update(id: number, updateDto: any) {
    await this.seoTemplateRepository.update(id, updateDto);
    return this.findOne(id);
  }

  async upsert(key: string, data: any) {
    let template = await this.seoTemplateRepository.findOne({
      where: { templateKey: key },
    });
    if (template) {
      await this.seoTemplateRepository.update(template.id, data);
      return this.findOne(template.id);
    } else {
      const newTemplate = this.seoTemplateRepository.create({
        ...data,
        templateKey: key,
      });
      return this.seoTemplateRepository.save(newTemplate);
    }
  }

  async remove(id: number) {
    const template = await this.findOne(id);
    return this.seoTemplateRepository.remove(template);
  }

  async removeByKey(key: string) {
    const template = await this.seoTemplateRepository.findOne({
      where: { templateKey: key },
    });
    if (!template)
      throw new NotFoundException(`Template with key ${key} not found`);
    return this.seoTemplateRepository.remove(template);
  }
}
