package org.raddatz.familienarchiv.user;

import org.raddatz.familienarchiv.document.BackfillResult;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.document.DocumentService;
import org.raddatz.familienarchiv.document.DocumentVersionService;
import org.raddatz.familienarchiv.importing.CanonicalImportOrchestrator;
import org.raddatz.familienarchiv.importing.ImportStatus;
import org.raddatz.familienarchiv.document.ThumbnailBackfillService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/admin")
@RequirePermission(Permission.ADMIN)
@RequiredArgsConstructor
public class AdminController {

    private final CanonicalImportOrchestrator importOrchestrator;
    private final DocumentService documentService;
    private final DocumentVersionService documentVersionService;
    private final ThumbnailBackfillService thumbnailBackfillService;

    @PostMapping("/trigger-import")
    public ResponseEntity<ImportStatus> triggerMassImport() {
        importOrchestrator.runImportAsync();
        return ResponseEntity.accepted().body(importOrchestrator.getStatus());
    }

    @GetMapping("/import-status")
    public ResponseEntity<ImportStatus> importStatus() {
        return ResponseEntity.ok(importOrchestrator.getStatus());
    }

    @PostMapping("/backfill-versions")
    public ResponseEntity<BackfillResult> backfillVersions() {
        int count = documentVersionService.backfillMissingVersions(
                documentService.getDocumentsWithoutVersions());
        return ResponseEntity.ok(new BackfillResult(count));
    }

    @PostMapping("/backfill-file-hashes")
    public ResponseEntity<BackfillResult> backfillFileHashes() {
        int count = documentService.backfillFileHashes();
        return ResponseEntity.ok(new BackfillResult(count));
    }

    @PostMapping("/backfill-titles")
    public ResponseEntity<BackfillResult> backfillTitles() {
        int count = documentService.backfillTitles();
        return ResponseEntity.ok(new BackfillResult(count));
    }

    @PostMapping("/generate-thumbnails")
    public ResponseEntity<ThumbnailBackfillService.BackfillStatus> generateThumbnails() {
        thumbnailBackfillService.runBackfillAsync();
        return ResponseEntity.accepted().body(thumbnailBackfillService.getStatus());
    }

    @GetMapping("/thumbnail-status")
    public ResponseEntity<ThumbnailBackfillService.BackfillStatus> thumbnailStatus() {
        return ResponseEntity.ok(thumbnailBackfillService.getStatus());
    }
}
