package com.home4j.resource;

import com.home4j.entity.Bookmark;
import com.home4j.entity.BookmarkGroup;
import com.home4j.service.BookmarkService;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import java.util.List;
import java.util.stream.Collectors;

/**
 * REST API 控制器 - 用于前端 AJAX 调用
 * 接收 JSON 数据，返回 JSON 响应
 */
@Path("/api/admin")
@RolesAllowed("ADMIN")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AdminApiResource {

    @Inject
    BookmarkService bookmarkService;

    // ==================== 分组 API ====================

    /**
     * 获取所有分组
     */
    @GET
    @Path("/groups")
    public Response getAllGroups() {
        List<BookmarkGroup> groups = bookmarkService.getAllGroups();
        List<GroupResponse> response = groups.stream()
                .map(GroupResponse::from)
                .collect(Collectors.toList());
        return Response.ok(response).build();
    }

    /**
     * 获取单个分组
     */
    @GET
    @Path("/groups/{id}")
    public Response getGroup(@PathParam("id") Long id) {
        BookmarkGroup group = BookmarkGroup.findById(id);
        if (group == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("分组不存在"))
                    .build();
        }
        return Response.ok(GroupResponse.from(group)).build();
    }

    /**
     * 创建分组
     */
    @POST
    @Path("/groups")
    public Response createGroup(GroupRequest request) {
        if (request.name == null || request.name.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("分组名称不能为空"))
                    .build();
        }
        
        BookmarkGroup group = bookmarkService.createGroup(
                request.name.trim(),
                request.icon != null ? request.icon.trim() : "folder"
        );
        
        // 如果有 sortOrder，更新它
        if (request.sortOrder != null) {
            group.sortOrder = request.sortOrder;
            group.persist();
        }
        
        return Response.status(Response.Status.CREATED)
                .entity(GroupResponse.from(group))
                .build();
    }

    /**
     * 更新分组
     */
    @PUT
    @Path("/groups/{id}")
    public Response updateGroup(@PathParam("id") Long id, GroupRequest request) {
        BookmarkGroup group = BookmarkGroup.findById(id);
        if (group == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("分组不存在"))
                    .build();
        }
        
        if (request.name == null || request.name.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("分组名称不能为空"))
                    .build();
        }
        
        bookmarkService.updateGroup(
                id,
                request.name.trim(),
                request.icon != null ? request.icon.trim() : group.icon,
                request.visible
        );
        
        // 更新 sortOrder
        if (request.sortOrder != null) {
            group.sortOrder = request.sortOrder;
            group.persist();
        }
        
        return Response.ok(GroupResponse.from(group)).build();
    }

    /**
     * 删除分组
     */
    @DELETE
    @Path("/groups/{id}")
    public Response deleteGroup(@PathParam("id") Long id) {
        boolean deleted = bookmarkService.deleteGroup(id);
        if (!deleted) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("分组不存在"))
                    .build();
        }
        return Response.ok(new SuccessResponse("删除成功")).build();
    }

    // ==================== 书签 API ====================

    /**
     * 获取所有书签
     */
    @GET
    @Path("/bookmarks")
    public Response getAllBookmarks() {
        List<Bookmark> bookmarks = Bookmark.listAll();
        List<BookmarkResponse> response = bookmarks.stream()
                .map(BookmarkResponse::from)
                .collect(Collectors.toList());
        return Response.ok(response).build();
    }

    /**
     * 获取单个书签
     */
    @GET
    @Path("/bookmarks/{id}")
    public Response getBookmark(@PathParam("id") Long id) {
        Bookmark bookmark = Bookmark.findById(id);
        if (bookmark == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("书签不存在"))
                    .build();
        }
        return Response.ok(BookmarkResponse.from(bookmark)).build();
    }

    /**
     * 创建书签
     */
    @POST
    @Path("/bookmarks")
    public Response createBookmark(BookmarkRequest request) {
        // 验证必填字段
        if (request.name == null || request.name.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("书签名称不能为空"))
                    .build();
        }
        if (request.url == null || request.url.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("URL不能为空"))
                    .build();
        }
        
        // 验证分组是否存在
        if (request.groupId != null) {
            BookmarkGroup group = BookmarkGroup.findById(request.groupId);
            if (group == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .entity(new ErrorResponse("指定的分组不存在"))
                        .build();
            }
        }
        
        Bookmark bookmark = bookmarkService.createBookmark(
                request.groupId,
                request.name.trim(),
                request.url.trim(),
                request.description != null ? request.description.trim() : null,
                request.icon != null ? request.icon.trim() : "link",
                request.openInNewTab != null ? request.openInNewTab : true,
                request.displayMode != null ? request.displayMode : "icon",
                request.backgroundImage != null ? request.backgroundImage.trim() : null
        );
        
        return Response.status(Response.Status.CREATED)
                .entity(BookmarkResponse.from(bookmark))
                .build();
    }

    /**
     * 更新书签
     */
    @PUT
    @Path("/bookmarks/{id}")
    public Response updateBookmark(@PathParam("id") Long id, BookmarkRequest request) {
        Bookmark bookmark = Bookmark.findById(id);
        if (bookmark == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("书签不存在"))
                    .build();
        }
        
        // 验证必填字段
        if (request.name == null || request.name.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("书签名称不能为空"))
                    .build();
        }
        if (request.url == null || request.url.trim().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("URL不能为空"))
                    .build();
        }
        
        // 验证分组是否存在
        if (request.groupId != null) {
            BookmarkGroup group = BookmarkGroup.findById(request.groupId);
            if (group == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .entity(new ErrorResponse("指定的分组不存在"))
                        .build();
            }
        }
        
        bookmarkService.updateBookmark(
                id,
                request.groupId,
                request.name.trim(),
                request.url.trim(),
                request.description != null ? request.description.trim() : null,
                request.icon != null ? request.icon.trim() : bookmark.icon,
                request.visible,
                request.openInNewTab,
                request.displayMode,
                request.backgroundImage != null ? request.backgroundImage.trim() : null
        );
        
        // 重新获取更新后的书签
        bookmark = Bookmark.findById(id);
        return Response.ok(BookmarkResponse.from(bookmark)).build();
    }

    /**
     * 删除书签
     */
    @DELETE
    @Path("/bookmarks/{id}")
    public Response deleteBookmark(@PathParam("id") Long id) {
        boolean deleted = bookmarkService.deleteBookmark(id);
        if (!deleted) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorResponse("书签不存在"))
                    .build();
        }
        return Response.ok(new SuccessResponse("删除成功")).build();
    }

    // ==================== DTO 类 ====================

    /**
     * 分组请求 DTO
     */
    public static class GroupRequest {
        public Long id;
        public String name;
        public String icon;
        public Integer sortOrder;
        public Boolean visible;
    }

    /**
     * 分组响应 DTO
     */
    public static class GroupResponse {
        public Long id;
        public String name;
        public String icon;
        public Integer sortOrder;
        public Boolean visible;

        public static GroupResponse from(BookmarkGroup group) {
            GroupResponse response = new GroupResponse();
            response.id = group.id;
            response.name = group.name;
            response.icon = group.icon;
            response.sortOrder = group.sortOrder;
            response.visible = group.visible;
            return response;
        }
    }

    /**
     * 书签请求 DTO
     */
    public static class BookmarkRequest {
        public Long id;
        public String name;
        public String url;
        public String description;
        public String icon;
        public Long groupId;
        public Boolean openInNewTab;
        public Boolean visible;
        public String displayMode;
        public String backgroundImage;
    }

    /**
     * 书签响应 DTO
     */
    public static class BookmarkResponse {
        public Long id;
        public String name;
        public String url;
        public String description;
        public String icon;
        public Long groupId;
        public Boolean openInNewTab;
        public Boolean visible;
        public String displayMode;
        public String backgroundImage;

        public static BookmarkResponse from(Bookmark bookmark) {
            BookmarkResponse response = new BookmarkResponse();
            response.id = bookmark.id;
            response.name = bookmark.name;
            response.url = bookmark.url;
            response.description = bookmark.description;
            response.icon = bookmark.icon;
            response.groupId = bookmark.group != null ? bookmark.group.id : null;
            response.openInNewTab = bookmark.openInNewTab;
            response.visible = bookmark.visible;
            response.displayMode = bookmark.displayMode;
            response.backgroundImage = bookmark.backgroundImage;
            return response;
        }
    }

    /**
     * 错误响应 DTO
     */
    public static class ErrorResponse {
        public boolean success = false;
        public String message;

        public ErrorResponse(String message) {
            this.message = message;
        }
    }

    /**
     * 成功响应 DTO
     */
    public static class SuccessResponse {
        public boolean success = true;
        public String message;

        public SuccessResponse(String message) {
            this.message = message;
        }
    }
}
