import { Controller, Post, Body, Get, Param, Delete, Patch, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Rule } from '../entities/rule.entity';
import { CreateRuleDto } from '../dto/create-rule.dto';
import { RuleEngineService } from '../services/rule-engine.service';
import { User } from '../../users/entities/user.entity';

@ApiTags('automation')
@Controller('automation')
export class AutomationController {
  private readonly logger = new Logger(AutomationController.name);

  constructor(
    @InjectRepository(Rule)
    private readonly ruleRepository: Repository<Rule>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly ruleEngineService: RuleEngineService,
  ) {}

  @Post('rules')
  @ApiOperation({ summary: 'Create a new automation rule | إنشاء قاعدة أتمتة جديدة' })
  async createRule(@Body() dto: CreateRuleDto) {
    const user = await this.userRepository.findOne({ where: { id: dto.userId } });
    if (!user) throw new Error('User not found');

    const rule = this.ruleRepository.create({
      ...dto,
      user,
      targetId: dto.targetId || 'all',
    });

    return this.ruleRepository.save(rule);
  }

  @Get('rules/:userId')
  @ApiOperation({ summary: 'Get all rules for a user | جلب جميع القواعد للمستخدم' })
  async getRules(@Param('userId') userId: string) {
    return this.ruleRepository.find({
      where: { user: { id: userId } },
      order: { createdAt: 'DESC' },
    });
  }

  @Post('process/:platform')
  @ApiOperation({ summary: 'Manually trigger rule processing | تشغيل يدوي لمعالجة القواعد' })
  async triggerProcess(@Param('platform') platform: 'meta' | 'tiktok' | 'google') {
    this.logger.log(`Manual trigger for rule processing: ${platform}`);
    // This would normally run via a Cron job every 15-60 minutes
    await this.ruleEngineService.processActiveRules(platform);
    return { status: 'success', message: `Rules processed for ${platform}` };
  }

  @Delete('rules/:id')
  @ApiOperation({ summary: 'Delete a rule | حذف قاعدة' })
  async deleteRule(@Param('id') id: string) {
    await this.ruleRepository.delete(id);
    return { status: 'deleted' };
  }
}
