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

// 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 firstName : string | null = payload.firstName as string | null,
        lastName : string | null = payload.lastName as string | null,
        jobType : boolean | null = payload.jobType as boolean | null,
        monthlySalary : number | null = payload.monthlySalary as number | null,
        gendre : string | null = payload.gendre as string | null,
        phone : string | null = payload.phone as string | null,
        email : string | null = payload.email as string | null,
        address : string | null = payload.address as string | null;
        // save the doc
        const doc = new workerModel({
            firstName,
            lastName,
            jobType,
            monthlySalary,
            gendre,
            phone,
            email,
            address
        })
        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)
    {
        console.log("e" , 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) * 10, 10];
            // get the docs
            const docs = await workerModel.find({}).skip(range[0]).limit(range[1]),
            // get the size of the docs
            docs_count = await workerModel.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 workerModel.find({
                $or: [
                    // search by ( case insensitive search )
                    { firstName: { $regex: searchKeyword, $options: 'i' } },
                    { lastName: { $regex: searchKeyword, $options: 'i' } },
                    { email: { $regex: searchKeyword, $options: 'i' } },
                    { phone: { $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) * 10, 10];
        // delete the doc
        await workerModel.findByIdAndRemove(_id)
        // get the docs by page
        const docs = await workerModel.find({}).skip(range[0]).limit(range[1]),
        // get the size of the docs
        docs_count = await workerModel.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 firstName : string | null = payload.firstName as string | null,
        lastName : string | null = payload.lastName as string | null,
        jobType : boolean | null = payload.jobType as boolean | null,
        monthlySalary : number | null = payload.monthlySalary as number | null,
        gendre : string | null = payload.gendre as string | null,
        phone : string | null = payload.phone as string | null,
        email : string | null = payload.email as string | null,
        address : string | null = payload.address as string | null,
        _id : string | null = payload._id as string | null;
        // update the doc
        let updated_doc = await workerModel.findByIdAndUpdate(_id , {
            firstName,
            lastName,
            jobType,
            monthlySalary,
            gendre,
            phone,
            email,
            address
        }, { 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"
            }
        })
    }
}