-- Migration: Create applications table
-- Description: Job applications (can be from registered users or guests)

CREATE TABLE IF NOT EXISTS applications (
    id SERIAL PRIMARY KEY,
    job_id INT NOT NULL,
    user_id INT,  -- NULL for guest applications
    
    -- Applicant Info (required for guest applications)
    name VARCHAR(255),
    phone VARCHAR(30),
    line_id VARCHAR(100),
    whatsapp VARCHAR(30),
    email VARCHAR(255),
    
    -- Application Content
    message TEXT,
    resume_url TEXT,
    documents JSONB,  -- Array of document objects {type: string, url: string}
    
    -- Status & Notes
    status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'reviewed', 'shortlisted', 'rejected', 'hired')),
    notes TEXT,  -- Recruiter notes
    
    -- Metadata
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign keys
    FOREIGN KEY (job_id) REFERENCES jobs(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
);

-- Indexes
CREATE INDEX idx_applications_job ON applications(job_id);
CREATE INDEX idx_applications_user ON applications(user_id);
CREATE INDEX idx_applications_status ON applications(status);
CREATE INDEX idx_applications_created_at ON applications(created_at DESC);

-- Comments
COMMENT ON TABLE applications IS 'Job applications from users or guests';
COMMENT ON COLUMN applications.user_id IS 'NULL if guest application';
COMMENT ON COLUMN applications.documents IS 'JSON array of uploaded documents (residence card, resume, etc.)';
COMMENT ON COLUMN applications.notes IS 'Internal notes from recruiters';
