package net.siegeln.cameleer.saas.portal;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tenant/sso")
public class TenantSsoController {

    private final TenantSsoService ssoService;

    public TenantSsoController(TenantSsoService ssoService) {
        this.ssoService = ssoService;
    }

    public record CreateSsoConnectorRequest(
        String providerName,
        String connectorName,
        Map<String, Object> config,
        List<String> domains
    ) {}

    @GetMapping
    public ResponseEntity<List<Map<String, Object>>> list() {
        return ResponseEntity.ok(ssoService.listConnectors());
    }

    @PostMapping
    public ResponseEntity<Map<String, Object>> create(@RequestBody CreateSsoConnectorRequest request) {
        var connector = ssoService.createConnector(
            request.providerName(), request.connectorName(),
            request.config(), request.domains());
        return ResponseEntity.status(HttpStatus.CREATED).body(connector);
    }

    @GetMapping("/{connectorId}")
    public ResponseEntity<Map<String, Object>> get(@PathVariable String connectorId) {
        return ResponseEntity.ok(ssoService.getConnector(connectorId));
    }

    @PatchMapping("/{connectorId}")
    public ResponseEntity<Map<String, Object>> update(@PathVariable String connectorId,
                                                       @RequestBody Map<String, Object> updates) {
        return ResponseEntity.ok(ssoService.updateConnector(connectorId, updates));
    }

    @DeleteMapping("/{connectorId}")
    public ResponseEntity<Void> delete(@PathVariable String connectorId) {
        ssoService.deleteConnector(connectorId);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/{connectorId}/test")
    public ResponseEntity<Map<String, Object>> test(@PathVariable String connectorId) {
        return ResponseEntity.ok(ssoService.testConnector(connectorId));
    }
}
