import { Response, NextFunction } from 'express';
import { AuthRequest } from '../../shared/middleware/auth';
import { contactsService } from './contacts.service';
import { ResponseFormatter } from '../../shared/utils/responseFormatter';

class ContactsController {
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const data = {
        ...req.body,
        createdById: req.user!.id,
      };
      
      const contact = await contactsService.create(data, req.user!.id);
      
      res.status(201).json(
        ResponseFormatter.success(contact, 'تم إنشاء جهة الاتصال بنجاح - Contact created successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async findAll(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const pageSize = parseInt(req.query.pageSize as string) || 20;
      
      const filters = {
        search: req.query.search as string,
        type: req.query.type as string,
        status: req.query.status as string,
        category: req.query.category as string,
        source: req.query.source as string,
        rating: req.query.rating ? parseInt(req.query.rating as string) : undefined,
        createdFrom: req.query.createdFrom ? new Date(req.query.createdFrom as string) : undefined,
        createdTo: req.query.createdTo ? new Date(req.query.createdTo as string) : undefined,
        excludeSuppliers: req.query.excludeSuppliers === 'true',
      };
      
      const result = await contactsService.findAll(filters, page, pageSize);
      
      res.json(ResponseFormatter.paginated(
        result.contacts,
        result.total,
        result.page,
        result.pageSize
      ));
    } catch (error) {
      next(error);
    }
  }

  async findById(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contact = await contactsService.findById(req.params.id);
      res.json(ResponseFormatter.success(contact));
    } catch (error) {
      next(error);
    }
  }

  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contact = await contactsService.update(
        req.params.id,
        req.body,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(contact, 'تم تحديث جهة الاتصال بنجاح - Contact updated successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async archive(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contact = await contactsService.archive(
        req.params.id,
        req.user!.id,
        req.body.reason
      );
      
      res.json(
        ResponseFormatter.success(contact, 'تم أرشفة جهة الاتصال بنجاح - Contact archived successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async delete(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      // This should be restricted by permissions - only GM can hard delete
      const contact = await contactsService.delete(
        req.params.id,
        req.user!.id,
        req.body.reason
      );
      
      res.json(
        ResponseFormatter.success(contact, 'تم حذف جهة الاتصال نهائياً - Contact deleted permanently')
      );
    } catch (error) {
      next(error);
    }
  }

  async merge(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { sourceId, targetId, reason } = req.body;
      
      const result = await contactsService.merge(
        sourceId,
        targetId,
        req.user!.id,
        reason
      );
      
      res.json(
        ResponseFormatter.success(result, 'تم دمج جهات الاتصال بنجاح - Contacts merged successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async addRelationship(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { toContactId, type, startDate, endDate, notes } = req.body;
      
      const relationship = await contactsService.addRelationship(
        req.params.id,
        toContactId,
        type,
        new Date(startDate),
        req.user!.id,
        endDate ? new Date(endDate) : undefined,
        notes
      );
      
      res.status(201).json(
        ResponseFormatter.success(relationship, 'تم إضافة العلاقة بنجاح - Relationship added successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async getRelationships(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const relationships = await contactsService.getRelationships(req.params.id);
      res.json(ResponseFormatter.success(relationships));
    } catch (error) {
      next(error);
    }
  }

  async updateRelationship(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { type, startDate, endDate, notes, isActive } = req.body;
      const data: any = {};
      
      if (type) data.type = type;
      if (startDate) data.startDate = new Date(startDate);
      if (endDate) data.endDate = new Date(endDate);
      if (notes !== undefined) data.notes = notes;
      if (isActive !== undefined) data.isActive = isActive;

      const relationship = await contactsService.updateRelationship(
        req.params.relationshipId,
        data,
        req.user!.id
      );

      res.json(
        ResponseFormatter.success(relationship, 'تم تحديث العلاقة بنجاح - Relationship updated successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async deleteRelationship(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      await contactsService.deleteRelationship(
        req.params.relationshipId,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(null, 'تم حذف العلاقة بنجاح - Relationship deleted successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async getHistory(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const history = await contactsService.getHistory(req.params.id);
      res.json(ResponseFormatter.success(history));
    } catch (error) {
      next(error);
    }
  }

  async import(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      if (!req.file) {
        return res.status(400).json(
          ResponseFormatter.error('ملف مطلوب - File required')
        );
      }

      const result = await contactsService.import(
        req.file.buffer,
        req.user!.id
      );

      res.json(
        ResponseFormatter.success(
          result,
          `تم استيراد ${result.success} جهة اتصال بنجاح - Imported ${result.success} contacts successfully`
        )
      );
    } catch (error) {
      next(error);
    }
  }

  async export(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const filters = {
        search: req.query.search as string,
        type: req.query.type as string,
        status: req.query.status as string,
        source: req.query.source as string,
        category: req.query.category as string,
        rating: req.query.rating ? parseInt(req.query.rating as string) : undefined,
        excludeCompanyEmployees: req.query.excludeCompanyEmployees === 'true',
        excludeSuppliers: req.query.excludeSuppliers === 'true',
      };

      const buffer = await contactsService.export(filters);

      res.setHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.setHeader(
        'Content-Disposition',
        `attachment; filename=contacts-${Date.now()}.xlsx`
      );
      res.send(buffer);
    } catch (error) {
      next(error);
    }
  }

  async checkDuplicates(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { email, phone, mobile, taxNumber, commercialRegister, excludeId } = req.body;

      const duplicates = await contactsService.findDuplicates(
        { email, phone, mobile, taxNumber, commercialRegister },
        excludeId
      );

      res.json(
        ResponseFormatter.success(
          duplicates,
          duplicates.length > 0 
            ? `تم العثور على ${duplicates.length} جهات اتصال مشابهة - Found ${duplicates.length} similar contacts`
            : 'لا توجد تكرارات - No duplicates found'
        )
      );
    } catch (error) {
      next(error);
    }
  }
}

export const contactsController = new ContactsController();

