import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateContentManagementDto } from './dto/create-content_management.dto';
import { UpdateContentManagementDto } from './dto/update-content_management.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ContentManagement } from './entities/content_management.entity';
import { Repository } from 'typeorm';
import { ContentManagementRepository } from './content_managements.repository';
import { lan } from 'src/lan';
import { isEmpty } from 'src/common/helper';

@Injectable()
export class ContentManagementsService {
  constructor(
    @InjectRepository(ContentManagement)
    private readonly contentEntity: Repository<ContentManagement>,
    private readonly contentRepository: ContentManagementRepository,
  ) {}

  async findType(type: string) {
    const data = await this.contentRepository.findOne(type);

    if (isEmpty(data)) {
      throw new NotFoundException(lan('type.not_found'));
    }

    return data;
  }

  async update(
    type: string,
    updateContentDto: UpdateContentManagementDto,
  ): Promise<ContentManagement> {
    let contentData = await this.contentRepository.findOne(type);

    if (!contentData) {
      const createStaticDto: CreateContentManagementDto = {
        type,
        content: updateContentDto.content,
      };

      return await this.contentEntity.save(createStaticDto);
    } else {
      if (updateContentDto.type) {
        contentData.type = updateContentDto.type;
      }

      if (updateContentDto.content) {
        contentData.content = updateContentDto.content;
      }

      if (
        updateContentDto.status !== undefined &&
        updateContentDto.status !== null
      ) {
        contentData.status = updateContentDto.status;
      }

      await this.contentEntity.save(contentData);
    }

    return contentData;
  }

  async removeContent(type: string) {
    const data = await this.contentRepository.findOne(type);

    if (isEmpty(data)) {
      throw new NotFoundException(lan('type.not_found'));
    }

    const { id, ...other } = data;

    return this.contentEntity.softDelete(id);
  }
}
