package com.home4j.resource;

import com.home4j.entity.BookmarkGroup;
import com.home4j.service.BookmarkService;
import com.home4j.service.ConfigService;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;

import java.util.List;

/**
 * 首页控制器 - 公开访问
 */
@Path("/")
public class IndexResource {

    @Inject
    Template index;

    @Inject
    BookmarkService bookmarkService;

    @Inject
    ConfigService configService;

    @Inject
    SecurityIdentity securityIdentity;

    /**
     * 首页 - 显示所有可见分组和书签
     */
    @GET
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance index() {
        List<BookmarkGroup> groups = bookmarkService.getAllVisibleGroupsWithBookmarks();
        List<BookmarkGroup> allGroups = bookmarkService.getAllGroups(); // 用于编辑模式
        
        // 检查用户是否已登录
        boolean isLoggedIn = !securityIdentity.isAnonymous();
        String username = isLoggedIn ? securityIdentity.getPrincipal().getName() : null;
        boolean isAdmin = securityIdentity.hasRole("ADMIN");
        
        // 构建 config 对象
        var config = new java.util.HashMap<String, Object>();
        config.put("siteTitle", configService.getSiteTitle());
        config.put("siteSubtitle", configService.getSiteSubtitle());
        config.put("theme", configService.getTheme());
        config.put("footerText", configService.getFooterText());
        
        return index
                .data("groups", groups)
                .data("allGroups", allGroups)
                .data("config", config)
                .data("siteTitle", configService.getSiteTitle())
                .data("siteSubtitle", configService.getSiteSubtitle())
                .data("theme", configService.getTheme())
                .data("footerText", configService.getFooterText())
                .data("searchEngine", configService.getSearchEngine())
                .data("showSearch", configService.isShowSearch())
                .data("viewMode", configService.getViewMode())
                .data("columns", configService.getColumns())
                .data("backgroundImage", configService.getBackgroundImage())
                .data("backgroundOverlay", configService.getBackgroundOverlay())
                .data("isLoggedIn", isLoggedIn)
                .data("isAdmin", isAdmin)
                .data("username", username);
    }

    /**
     * 搜索书签 API
     */
    @GET
    @Path("/api/search")
    @Produces(MediaType.APPLICATION_JSON)
    public List<?> search(@QueryParam("q") String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return List.of();
        }
        return bookmarkService.searchBookmarks(keyword.trim());
    }
}
