import { Controller, Post, Route, SuccessResponse, Body, Middlewares } from "tsoa";
import { ApiValidationError } from "../../Models/Server.Error.model";
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
import { authenticateMiddleware } from "../../middleware/authentication";
import {
    DeletePostParams,
    GetPostParams,
    IPost,
    PaginatePostsParams,
    PaginatePostsResults,
    SavePostParams,
} from "../../Models/Posts/Posts.Interface";
import { PostsService } from "./Posts.Service";

@Route("posts")
export class PostsController extends Controller {
    @SuccessResponse(201, "Saved")
    @Post("save")
    @Middlewares(authenticateMiddleware)
    public async savePost(
        @Body() requestBody: SavePostParams
    ): Promise<IPost | ApiValidationError> {
        try {
            const post = await new PostsService().savePost(requestBody);
            this.setStatus(201);
            return post;
        } catch (e) {
            const errorOccurred: Error = e as Error;
            this.setStatus(500);
            return new ApiValidationError(500, errorOccurred.message);
        }
    }

    @SuccessResponse(200, "Done")
    @Post("delete")
    @Middlewares(authenticateMiddleware)
    public async deletePost(
        @Body() requestBody: DeletePostParams
    ): Promise<ApiVoidResult | ApiValidationError> {
        try {
            await new PostsService().deletePost(requestBody);
            this.setStatus(200);
            return { success: true, message: "Post borrado correctamente." };
        } catch (e) {
            const errorOccurred: Error = e as Error;
            this.setStatus(500);
            return new ApiValidationError(500, errorOccurred.message);
        }
    }

    @SuccessResponse(200, "Done")
    @Post("paginate")
    public async paginate(
        @Body() requestBody: PaginatePostsParams
    ): Promise<PaginatePostsResults | ApiValidationError> {
        try {
            const result = await new PostsService().paginate(requestBody);
            this.setStatus(200);
            return result;
        } catch (e) {
            const errorOccurred: Error = e as Error;
            this.setStatus(500);
            return new ApiValidationError(500, errorOccurred.message);
        }
    }

    @SuccessResponse(200, "Done")
    @Post("get-post")
    public async getPost(
        @Body() requestBody: GetPostParams
    ): Promise<IPost | ApiValidationError> {
        try {
            const result = await new PostsService().getPost(requestBody);
            this.setStatus(200);
            return result;
        } catch (e) {
            const errorOccurred: Error = e as Error;
            this.setStatus(500);
            return new ApiValidationError(500, errorOccurred.message);
        }
    }
}

//
