package com.saas.admin.controller;

import com.saas.admin.entity.PhoneNumber;
import com.saas.admin.service.PhoneNumberService;
import com.saas.shared.enums.Provider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/phone-numbers")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
@RequiredArgsConstructor
@Slf4j
public class AdminPhoneNumberController {

    private final PhoneNumberService phoneNumberService;

    @PostMapping
    public ResponseEntity<PhoneNumber> createPhoneNumber(@RequestBody PhoneNumber phoneNumber) {
        log.info("📞 Admin creating phone number: {} for tenant: {}", 
                phoneNumber.getPhoneNumber(), phoneNumber.getTenantId());
        PhoneNumber created = phoneNumberService.createPhoneNumber(phoneNumber);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<PhoneNumber> getPhoneNumberById(@PathVariable Long id) {
        return phoneNumberService.getPhoneNumberById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    public ResponseEntity<List<PhoneNumber>> getAllPhoneNumbers(
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) Provider provider,
            @RequestParam(required = false) Boolean isActive) {
        
        log.info("📋 Fetching phone numbers - tenantId: {}, provider: {}, isActive: {}", 
                tenantId, provider, isActive);
        
        List<PhoneNumber> phoneNumbers;
        
        if (tenantId != null && provider != null) {
            phoneNumbers = phoneNumberService.getPhoneNumbersByTenant(tenantId, provider);
        } else if (tenantId != null) {
            phoneNumbers = phoneNumberService.getPhoneNumbersByTenant(tenantId);
        } else if (provider != null) {
            phoneNumbers = phoneNumberService.getAllPhoneNumbersByProvider(provider);
        } else if (isActive != null) {
            phoneNumbers = phoneNumberService.getPhoneNumbersByActiveStatus(isActive);
        } else {
            phoneNumbers = phoneNumberService.getAllPhoneNumbers();
        }
        
        return ResponseEntity.ok(phoneNumbers);
    }

    @PutMapping("/{id}")
    public ResponseEntity<PhoneNumber> updatePhoneNumber(
            @PathVariable Long id,
            @RequestBody PhoneNumber updates) {
        
        log.info("✏️ Admin updating phone number ID: {}", id);
        try {
            PhoneNumber updated = phoneNumberService.updatePhoneNumber(id, updates);
            return ResponseEntity.ok(updated);
        } catch (RuntimeException e) {
            log.error("❌ Phone number not found: {}", id);
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePhoneNumber(@PathVariable Long id) {
        log.info("🗑️ Admin deleting phone number ID: {}", id);
        phoneNumberService.deletePhoneNumber(id);
        return ResponseEntity.noContent().build();
    }

    @PatchMapping("/{id}/deactivate")
    public ResponseEntity<Void> deactivatePhoneNumber(@PathVariable Long id) {
        log.info("⛔ Admin deactivating phone number ID: {}", id);
        phoneNumberService.deactivatePhoneNumber(id);
        return ResponseEntity.ok().build();
    }

    @PatchMapping("/{id}/activate")
    public ResponseEntity<Void> activatePhoneNumber(@PathVariable Long id) {
        log.info("✅ Admin activating phone number ID: {}", id);
        phoneNumberService.activatePhoneNumber(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/tenant/{tenantId}")
    public ResponseEntity<List<PhoneNumber>> getPhoneNumbersByTenant(@PathVariable String tenantId) {
        log.info("📋 Fetching all phone numbers for tenant: {}", tenantId);
        List<PhoneNumber> phoneNumbers = phoneNumberService.getPhoneNumbersByTenant(tenantId);
        return ResponseEntity.ok(phoneNumbers);
    }

    @GetMapping("/provider/{provider}")
    public ResponseEntity<List<PhoneNumber>> getPhoneNumbersByProvider(@PathVariable Provider provider) {
        log.info("📋 Fetching all {} phone numbers", provider);
        List<PhoneNumber> phoneNumbers = phoneNumberService.getAllPhoneNumbersByProvider(provider);
        return ResponseEntity.ok(phoneNumbers);
    }
}
