import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MockTemplates } from './entities/mock_templates.entity';

@Injectable()
export class MockTemplatesService {
  constructor(
    @InjectRepository(MockTemplates)
    private readonly mockTemplatesRepository: Repository<MockTemplates>,
  ) {}

  async findAll(roleId?: number) {
    try {
      const queryBuilder =
        this.mockTemplatesRepository.createQueryBuilder('mt');

      if (roleId) {
        queryBuilder.where('mt.role_id = :roleId', { roleId });
      }

      queryBuilder.orderBy('mt.created_at', 'DESC');

      const templates = await queryBuilder.getMany();

      return {
        success: true,
        data: templates,
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to fetch mock templates',
        error: error.message,
      };
    }
  }

  async findOne(id: number) {
    try {
      const template = await this.mockTemplatesRepository.findOne({
        where: { id },
      });

      if (!template) {
        return {
          success: false,
          message: 'Mock template not found',
        };
      }

      return {
        success: true,
        data: template,
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to fetch mock template',
        error: error.message,
      };
    }
  }

  async create(data: any) {
    try {
      const template = this.mockTemplatesRepository.create({
        role_id: data.role_id,
        title: data.title,
        total_questions: data.total_questions || 10,
        duration_minutes: data.duration_minutes || 30,
        allowed_difficulty: data.allowed_difficulty || [],
        required_skill_ids: data.required_skill_ids || [],
        is_active: data.is_active !== undefined ? data.is_active : true,
        created_by: data.created_by,
      });

      const saved = await this.mockTemplatesRepository.save(template);

      return {
        success: true,
        message: 'Mock template created successfully',
        data: saved,
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to create mock template',
        error: error.message,
      };
    }
  }

  async update(id: number, data: any) {
    try {
      const template = await this.mockTemplatesRepository.findOne({
        where: { id },
      });

      if (!template) {
        return {
          success: false,
          message: 'Mock template not found',
        };
      }

      // Update fields
      if (data.role_id !== undefined) template.role_id = data.role_id;
      if (data.title !== undefined) template.title = data.title;
      if (data.total_questions !== undefined)
        template.total_questions = data.total_questions;
      if (data.duration_minutes !== undefined)
        template.duration_minutes = data.duration_minutes;
      if (data.allowed_difficulty !== undefined)
        template.allowed_difficulty = data.allowed_difficulty;
      if (data.required_skill_ids !== undefined)
        template.required_skill_ids = data.required_skill_ids;
      if (data.is_active !== undefined) template.is_active = data.is_active;

      const updated = await this.mockTemplatesRepository.save(template);

      return {
        success: true,
        message: 'Mock template updated successfully',
        data: updated,
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to update mock template',
        error: error.message,
      };
    }
  }

  async delete(id: number) {
    try {
      const template = await this.mockTemplatesRepository.findOne({
        where: { id },
      });

      if (!template) {
        return {
          success: false,
          message: 'Mock template not found',
        };
      }

      await this.mockTemplatesRepository.remove(template);

      return {
        success: true,
        message: 'Mock template deleted successfully',
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to delete mock template',
        error: error.message,
      };
    }
  }

  async toggleStatus(id: number) {
    try {
      const template = await this.mockTemplatesRepository.findOne({
        where: { id },
      });

      if (!template) {
        return {
          success: false,
          message: 'Mock template not found',
        };
      }

      template.is_active = !template.is_active;
      const updated = await this.mockTemplatesRepository.save(template);

      return {
        success: true,
        message: `Mock template ${updated.is_active ? 'activated' : 'deactivated'} successfully`,
        data: updated,
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to toggle mock template status',
        error: error.message,
      };
    }
  }
}
