import dbConnect from "@/database/dbConnect";
import { NextResponse } from "next/server";
import equipmentModel from "@/database/models/equipmentModel";

// POST METHOD
export async function POST(req:Request)
{
    try{
        // connect to the db
        dbConnect();
        // get the request payload
        const { payload } = await req.json();
        // get data from formData
        const name : string | null = payload.name as string | null,
        description : string | null = payload.description as string | null,
        boughtAt_unix : number | null = payload.boughtAt_unix as number | null,
        quantity: number | null = payload.quantity as number | null,
        sallerName: string | null = payload.sallerName as string | null,
        sallerAddress: string | null = payload.sallerAddress as string | null,
        sallerPhone: string | null = payload.sallerPhone as string | null,
        singlePrice: number | null = payload.singlePrice as number | null;
        // save the doc
        const doc = new equipmentModel({
            name,
            description,
            boughtAt_unix,
            quantity,
            sallerName,
            sallerAddress,
            sallerPhone,
            singlePrice,
            addedAt: Math.floor(new Date().getTime() / 1000),
        })
        await doc.save()
        // return the success response with the new added doc
        return NextResponse.json({
            success: true,
            message: "requestTerminatedWithSuccess",
            data: doc,
        }, {
            status: 200,
            headers: {
                "content-type": "application/json"
            }
        })
    }catch(e)
    {
        // catch any error and return an error response
        return NextResponse.json({
            success: false,
            message: "serverError",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        })
    }
}
// set the revalidate variable
export const revalidate = 5;
// GET METHOD
export async function GET(req:Request)
{
    try{
        // connect to the db
        dbConnect();
        // get the parms
        const { searchParams } = new URL(req.url)
        const type = searchParams.get('type')
        // if get by page
        if(type=='page')
        {
            // get the page
            const page : string | null = searchParams.get('page') ? searchParams.get('page') : '0',
            range : number[] = [(parseInt(page?page : '0') - 1) * 4 , 4];
            // get the docs
            const docs = await equipmentModel.find({}).skip(range[0]).limit(range[1]),
            // get the size of the docs
            docs_count = await equipmentModel.countDocuments({});
            // prepare the return data
            return NextResponse.json({
                success: true,
                message: "docsGetedSuccessfully",
                data: {
                    docs,
                    docs_count,
                }
            })
        }
        // if type is search
        else if(type == 'search')
        {
            // get the searchKeyword param
            let searchKeyword = searchParams.get('searchKeyword')
            // get the search results docs
            let results = await equipmentModel.find({
                $or: [
                    // search by ( case insensitive search )
                    { name: { $regex: searchKeyword, $options: 'i' } },
                    { description: { $regex: searchKeyword, $options: 'i' } },
                    { sallerName: { $regex: searchKeyword, $options: 'i' } },
                    { sallerAddress: { $regex: searchKeyword, $options: 'i' } }
                ]
            })
            // get the docs
            let responseData = {
                docs: results,
                docs_count : results.length,
            }
            // return the response
            return NextResponse.json({
                success: true,
                message: "docsGetedSuccessfully",
                data: responseData ? responseData : [],
            } , {
                status: 200,
            })
        }
    }catch(e)
    {
        // catch any error and return an error response
        return NextResponse.json({
            success: false,
            message: "serverError",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        })
    }
}
// DELETE METHOD
export async function DELETE(req:Request)
{
    try{
        // connect to the db
        dbConnect();
        // get the parms
        const { searchParams } = new URL(req.url)
        const page = searchParams.get('page'),        
        _id : string | null = searchParams.get('_id'),
        range : number[] = [(parseInt(page?page : '0') - 1) * 4 , 4];
        // delete the doc
        await equipmentModel.findByIdAndRemove(_id)
        // get the docs by page
        const docs = await equipmentModel.find({}).skip(range[0]).limit(range[1]),
        // get the size of the docs
        docs_count = await equipmentModel.countDocuments({});
        // prepare the return data
        return NextResponse.json({
            success: true,
            message: "docsGetedSuccessfully",
            data: {
                docs,
                docs_count,
            }
        })
    }catch(e)
    {
        // catch any error and return an error response
        return NextResponse.json({
            success: false,
            message: "serverError",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        })
    }
}
// PUT METHOD
export async function PUT(req:Request)
{
    try{
        // connect to the db
        dbConnect();
        // get the request payload
        const { payload } = await req.json();
        // get data from formData
        const name : string | null = payload.name as string | null,
        description : string | null = payload.description as string | null,
        boughtAt_unix : number | null = payload.boughtAt_unix as number | null,
        quantity: number | null = payload.quantity as number | null,
        sallerName: string | null = payload.sallerName as string | null,
        sallerAddress: string | null = payload.sallerAddress as string | null,
        sallerPhone: string | null = payload.sallerPhone as string | null,
        singlePrice: number | null = payload.singlePrice as number | null,
        _id : string | null = payload._id as string | null;
        // update the doc
        let updated_doc = await equipmentModel.findByIdAndUpdate(_id , {
            name,
            description,
            boughtAt_unix,
            quantity,
            sallerName,
            sallerAddress,
            sallerPhone,
            singlePrice,
        }, { new: true })
        // return the success response
        return NextResponse.json({
            success: true,
            message: "requestTerminatedWithSuccess",
            data: updated_doc,
        }, {
            status: 200,
            headers: {
                "content-type": "application/json"
            }
        })
    }catch(e)
    {
        // catch any error and return an error response
        return NextResponse.json({
            success: false,
            message: "serverError",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        })
    }
}